<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta property="og:type" content="website">
<meta property="og:title" content="一年春又来">
<meta property="og:url" content="http://littlefxc.github.io/page/20/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="一年春又来">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://littlefxc.github.io/page/20/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>
<title>一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">

    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/logback-Kafka-logstash%E9%9B%86%E6%88%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/26/logback-Kafka-logstash%E9%9B%86%E6%88%90/" class="post-title-link" itemprop="url">logback+Kafka+logstash集成</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 19:37:02" itemprop="dateCreated datePublished" datetime="2019-06-26T19:37:02+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-09-01 08:54:34" itemprop="dateModified" datetime="2021-09-01T08:54:34+08:00">2021-09-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/elk/" itemprop="url" rel="index"><span itemprop="name">elk</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>我们是通过 logback 打印日志，然后将日志通过 kafka 消息队列发送到 Logstash,经过处理以后存储到 Elasticsearch 中，然后通过 Kibana 图形化界面进行分析和处理。</p>
<p>在 spring boot 应用程序中，默认使用 logback 来记录日志，并用 INFO 级别输出日志到控制台。</p>
<p>日志级别和顺序：TRACE &lt; DEBUG &lt; INFO &lt; WARN &lt; ERROR &lt; FATAL</p>
<p>Spring Boot官方推荐优先使用带有-spring的文件名作为,按照如下规则组织配置文件名，就能被正确加载:</p>
<p>logback-spring.xml &gt; logback-spring.groovy &gt; logback.xml &gt; logback.groovy</p>
<h2 id="1-logback-与-Kafka-的集成"><a href="#1-logback-与-Kafka-的集成" class="headerlink" title="1. logback 与 Kafka 的集成"></a>1. logback 与 Kafka 的集成</h2><p>logback 记录日志到 Kafka 消息队列中去，主要使用的是 <code>com.github.danielwegener:logback-kafka-appender:0.2.0-RC2</code> 这个依赖.</p>
<h3 id="1-1-KafkaAppender-配置说明"><a href="#1-1-KafkaAppender-配置说明" class="headerlink" title="1.1. KafkaAppender 配置说明"></a>1.1. KafkaAppender 配置说明</h3><p>由于Logback Encoder API中的重大更改，您需要至少使用logback版本1.2。</p>
<p>确保项目依赖中有：</p>
<p>[maven pom.xml]</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;com.github.danielwegener&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;logback-kafka-appender&lt;&#x2F;artifactId&gt;</span><br><span class="line">    &lt;version&gt;0.2.0-RC2&lt;&#x2F;version&gt;</span><br><span class="line">    &lt;scope&gt;runtime&lt;&#x2F;scope&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;ch.qos.logback&lt;&#x2F;groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;logback-classic&lt;&#x2F;artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.2.3&lt;&#x2F;version&gt;</span><br><span class="line">    &lt;scope&gt;runtime&lt;&#x2F;scope&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br></pre></td></tr></table></figure>

<p>[maven pom.xml]</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- This is the kafkaAppender --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;kafkaAppender&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.KafkaAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">encoder</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">pattern</span>&gt;</span>%d&#123;HH:mm:ss.SSS&#125; [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="name">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">encoder</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">topic</span>&gt;</span>logs<span class="tag">&lt;/<span class="name">topic</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">keyingStrategy</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.keying.NoKeyKeyingStrategy&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">deliveryStrategy</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.delivery.AsynchronousDeliveryStrategy&quot;</span> /&gt;</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">&lt;!-- 可选参数, 用于固定分区 --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- &lt;partition&gt;0&lt;/partition&gt; --&gt;</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">&lt;!-- 可选参数，用于在kafka消息中包含日志时间戳 --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- &lt;appendTimestamp&gt;true&lt;/appendTimestamp&gt; --&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 每个&lt;producerConfig&gt;转换为常规kafka-client配置（格式：key = value） --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 生产者配置记录在这里：https//kafka.apache.org/documentation.html#newproducerconfigs --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- bootstrap.servers是唯一必需的 producerConfig --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>bootstrap.servers=localhost:9092<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 如果kafka不可用，这是后备appender。 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;STDOUT&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 标准输出 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;STDOUT&quot;</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.core.ConsoleAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">encoder</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">pattern</span>&gt;</span>%d&#123;HH:mm:ss.SSS&#125; [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="name">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">encoder</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">root</span> <span class="attr">level</span>=<span class="string">&quot;info&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;kafkaAppender&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">root</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="1-2-兼容性-Compatibility"><a href="#1-2-兼容性-Compatibility" class="headerlink" title="1.2. 兼容性:Compatibility"></a>1.2. 兼容性:Compatibility</h3><p>logback-kafka-appender 依赖于 <code>org.apache.kafka:kafka-clients:1.0.0:jar</code>。它可以将日志附加到版本为 <code>0.9.0.0</code> 或更高版本的 kafka 代理。</p>
<p>对 <code>kafka-clients</code> 的依赖性不会被遮蔽，并且可以通过依赖性覆盖升级到更高的 api 兼容版本。</p>
<h3 id="1-3-分发策略-Delivery-strategies"><a href="#1-3-分发策略-Delivery-strategies" class="headerlink" title="1.3. 分发策略:Delivery strategies"></a>1.3. 分发策略:Delivery strategies</h3><p>直接通过网络进行日志记录并不是一件容易的事情，因为它可能不如本地文件系统可靠，并且如果传输出现问题，对应用程序性能的影响要大得多。</p>
<p>您需要做出一个重要的决定：是将所有日志传递到远程 Kafka 更重要，还是让应用程序保持平稳运行更为重要？这两个决定都允许您调整此 appender 以获得吞吐量。</p>
<ul>
<li><p>AsynchronousDeliveryStrategy: </p>
<p>  将每个日志消息分派给Kafka生成器。如果由于某些原因传递失败，则将消息发送给 fallback appenders。<br>  但是，如果生产者发送的缓冲区已满，这个交付策略就会阻塞(如果到代理的连接丢失，就会发生这种情况)。<br>  为了避免这种阻塞，可以启用 <code>producerConfig</code> <code>block.buffer.full=false</code>。<br>  所有不能足够快地交付的日志消息都将立即转到 fallback appenders。</p>
</li>
<li><p>BlockingDeliveryStrategy: </p>
<p>  将每条日志消息分派给Kafka Producer。如果由于某些原因导致传递失败，则会将消息分派给备用追加程序(fallback appender)。<br>  但是，如果生成器发送缓冲区已满，则此DeliveryStrategy 阻止每个调用线程，直到实际传递日志消息。<br>  通常不鼓励这种策略，因为它对吞吐量有很大的负面影响。警告：此策略不应与 <code>producerConfig</code> 一起使用 <code>linger.ms</code></p>
</li>
</ul>
<h4 id="1-3-1-关于-broker-的中断"><a href="#1-3-1-关于-broker-的中断" class="headerlink" title="1.3.1. 关于 broker 的中断"></a>1.3.1. 关于 broker 的中断</h4><p>AsynchronousDeliveryStrategy 不会阻止被Kafka元数据交换阻塞的应用程序。<br>这意味着：如果在日志记录上下文启动时无法访问所有代理，或者所有代理在较长时间内无法访问（&gt; metadata.max.age.ms），<br>则 appender 最终将阻塞。这种行为通常是不受欢迎的，可以使用 kafka-clients 0.9 进行迁移（参见＃16）。<br>在此之前，您可以使用 logback 自己的 AsyncAppender 包装 KafkaAppender。</p>
<p>示例配置可能如下所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- This is the kafkaAppender --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;kafkaAppender&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.KafkaAppender&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Kafka Appender configuration --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;ASYNC&quot;</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.classic.AsyncAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;kafkaAppender&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">root</span> <span class="attr">level</span>=<span class="string">&quot;info&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;ASYNC&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">root</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="1-3-2-自定义分发策略-delivery-strategies"><a href="#1-3-2-自定义分发策略-delivery-strategies" class="headerlink" title="1.3.2. 自定义分发策略(delivery strategies)"></a>1.3.2. 自定义分发策略(delivery strategies)</h4><p>你可能使用自己的分发策略，只需继承 <code>com.github.danielwegener.logback.kafka.delivery.DeliveryStrategy</code></p>
<h4 id="1-3-3-备用追加程序-fallback-appender"><a href="#1-3-3-备用追加程序-fallback-appender" class="headerlink" title="1.3.3. 备用追加程序:fallback appender"></a>1.3.3. 备用追加程序:fallback appender</h4><p>如果由于某种原因，kafka-producer决定它无法发布日志消息，那么该消息仍然可以记录到 fallback appender（STDOUT 或 STDERR 上的 ConsoleAppender 将是一个合理的选择）。</p>
<p>只需将您的后备appender作为logback appender-ref添加到logback.xml中的KafkaAppender部分。 每个无法传递给kafka的消息都将写入所有已定义的appender-ref。</p>
<p>1.1 章节示例：<code>&lt;appender-ref ref =&quot;STDOUT&quot;&gt;</code> 中 <code>STDOUT</code> 是已定义的 appender。</p>
<p>请注意，AsynchronousDeliveryStrategy 将重用 kafka 生成器io线程将消息写入备用 appender。 因此，所有后备追加者应该是合理的快速，所以他们不会减慢或打破卡夫卡生产者。</p>
<h4 id="1-3-4-生产者调整"><a href="#1-3-4-生产者调整" class="headerlink" title="1.3.4. 生产者调整"></a>1.3.4. 生产者调整</h4><p>这个appender使用kafka-0.8.2中引入的 <a target="_blank" rel="noopener" href="https://kafka.apache.org/documentation.html#producerconfigs">kafka生成器</a>。 它使用生成器默认配置。</p>
<p>您可以使用 <code>&lt;producerConfig&gt; Name = Value &lt;/ producerConfig&gt;</code> 块覆盖任何已知的kafka生成器配置（请注意，boostrap.servers配置是必需的）。<br>这允许很多微调潜力（例如，使用batch.size，compression.type 和 linger.ms）。</p>
<h4 id="1-3-5-序列化"><a href="#1-3-5-序列化" class="headerlink" title="1.3.5. 序列化"></a>1.3.5. 序列化</h4><p>该模块支持任何 <code>ch.qos.logback.core.encoder.Encoder</code>。这允许您使用能够编码 <code>ILoggingEvent</code>或 <code>IAccessEvent</code> 的任何编码器，<br>如众所周知的<a target="_blank" rel="noopener" href="https://logback.qos.ch/manual/encoders.html#PatternLayoutEncoder">logback PatternLayoutEncoder</a>，<br>或者例如 <a target="_blank" rel="noopener" href="https://github.com/logstash/logstash-logback-encoder#usage">logstash-logback-encoder的LogstashEncoxer</a>。</p>
<h5 id="1-3-5-1-自定义序列化"><a href="#1-3-5-1-自定义序列化" class="headerlink" title="1.3.5.1 自定义序列化"></a>1.3.5.1 自定义序列化</h5><p>如果要在kafka日志记录主题上编写与字符串不同的内容，可以使用编码机制。 用例将是生产或消费方面的较小消息大小和/或更好的序列化/反序列化性能。<br>有用的格式可以是BSON，Avro或其他。</p>
<p>要推出自己的实现，请参阅<a target="_blank" rel="noopener" href="https://logback.qos.ch/xref/ch/qos/logback/core/encoder/Encoder.html">logback文档</a>。<br>请注意，logback-kafka-appender永远不会调用headerBytes（）或footerBytes（）方法。</p>
<p>您的编码器应该针对您要支持的事件类型的任何子类型（通常是 <code>ILoggingEvent</code>）进行类型参数化，例如:</p>
<p><code>public class MyEncoder extends ch.qos.logback.core.encoder.Encoder&lt;ILoggingEvent&gt; &#123;/*..*/&#125;</code></p>
<h3 id="1-4-键控策略-分区-Keying-strategies-Partitioning"><a href="#1-4-键控策略-分区-Keying-strategies-Partitioning" class="headerlink" title="1.4 键控策略/分区:Keying strategies / Partitioning"></a>1.4 键控策略/分区:Keying strategies / Partitioning</h3><p>Kafka的可扩展性和排序保证严重依赖于分区的概念（<a target="_blank" rel="noopener" href="https://kafka.apache.org/082/documentation.html#introduction">这里有更多细节</a>）。<br>对于应用程序日志记录，这意味着我们需要决定如何在多个kafka主题分区上分发日志消息。<br>这个决定的一个含义是消息在从任意多分区消费者消费时如何排序，因为kafka仅在每个单独的分区上提供有保证的读取顺序。<br>另一个含义是我们的日志消息在所有可用分区中的分布均匀，因此在多个代理之间保持平衡。</p>
<p>日志消息的顺序可能重要，也可能不重要，具体取决于预期的消费者 - 受众（例如，logstash索引器无论如何都会按时间戳重新排序所有消息）。</p>
<p>您可以使用partition属性为kafka appender提供固定分区，或让生产者使用消息密钥对消息进行分区。 因此logback-kafka-appender支持以下键控策略策略：</p>
<ul>
<li><p><code>NoKeyKeyingStrategy</code> : </p>
<p>  不生成 message key。如果未提供固定分区，则导致跨分区的循环分布。</p>
</li>
<li><p><code>HostNameKeyingStrategy</code> : </p>
<p>  此策略使用 HOSTNAME 作为 message key。 这很有用，因为它可以确保此主机发出的所有日志消息对于任何使用者都保持正确的顺序。<br>  但是这种策略可能导致少量主机的日志分配不均匀（与分区数量相比）。</p>
</li>
<li><p><code>ContextNameKeyingStrategy</code> : </p>
<p>  此策略使用 logback 的 CONTEXT_NAME 作为 message key。<br>  这可以确保由同一日志记录上下文记录的所有日志消息将保持在任何使用者的正确顺序中。<br>  但是这种策略可能导致少量主机的日志分配不均匀（与分区数量相比）。<br>  此策略仅适用于ILoggingEvents。</p>
</li>
<li><p><code>ThreadNameKeyingStrategy</code> : </p>
<p>  此策略使用调用线程名(thread name)称作为 message key。<br>  这可确保同一线程记录的所有消息将保持正确的顺序，供任何使用者使用。<br>  但是这种策略可能会导致少量线程（-names）的日志分配不均匀（与分区数量相比）。<br>  此策略仅适用于 ILoggingEvents。</p>
</li>
<li><p><code>LoggerNameKeyingStrategy</code> : </p>
<p>  *此策略使用记录器名称(logger name)作为 message key。<br>  这可确保同一记录器记录的所有消息都将保持在任何使用者的正确顺序中。<br>  但是这种策略可能会导致少量不同记录器的日志分配不均匀（与分区数量相比）。<br>  此策略仅适用于 ILoggingEvents。</p>
</li>
</ul>
<h4 id="1-4-1-自定义键控策略-Custom-keying-strategies"><a href="#1-4-1-自定义键控策略-Custom-keying-strategies" class="headerlink" title="1.4.1. 自定义键控策略 Custom keying strategies"></a>1.4.1. 自定义键控策略 Custom keying strategies</h4><p>如果上述键控策略都不满足您的要求，您可以通过实现自定义 KeyingStrategy 轻松实现自己的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> foo;</span><br><span class="line"><span class="keyword">import</span> com.github.danielwegener.logback.kafka.keying.KeyingStrategy;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 这是一个有效的例子，但并没有多大意义 */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LevelKeyingStrategy</span> <span class="keyword">implements</span> <span class="title">KeyingStrategy</span>&lt;<span class="title">ILoggingEvent</span>&gt; </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">byte</span>[] createKey(ILoggingEvent e) &#123;</span><br><span class="line">        <span class="keyword">return</span> ByteBuffer.allocate(<span class="number">4</span>).putInt(e.getLevel()).array();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>作为大多数自定义 logback 组件，您的自定义分区策略还可以实现 <code>ch.qos.logback.core.spi.ContextAware</code> 和 <code>ch.qos.logback.core.spi.LifeCycle</code> 接口。</p>
<p>当您想要使用kafka的日志压缩工具时，自定义键控策略可能会特别方便。</p>
<h3 id="1-5-logback-spring-xml-示例"><a href="#1-5-logback-spring-xml-示例" class="headerlink" title="1.5. logback-spring.xml 示例"></a>1.5. logback-spring.xml 示例</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span> <span class="attr">scan</span>=<span class="string">&quot;true&quot;</span> <span class="attr">scanPeriod</span>=<span class="string">&quot;60 seconds&quot;</span> <span class="attr">debug</span>=<span class="string">&quot;false&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">contextName</span>&gt;</span>oauth2-auth-server<span class="tag">&lt;/<span class="name">contextName</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;LOG_HOME&quot;</span> <span class="attr">value</span>=<span class="string">&quot;logs&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--输出到控制台--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;console&quot;</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.core.ConsoleAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">encoder</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">pattern</span>&gt;</span>%-12(%d&#123;yyyy-MM-dd HH:mm:ss.SSS&#125;) %contextName [%thread] %highlight(%-5level) %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="name">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">encoder</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--输出到kafka--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;kafka&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.KafkaAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">encoder</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.classic.encoder.PatternLayoutEncoder&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">pattern</span>&gt;</span>%-12(%d&#123;yyyy-MM-dd HH:mm:ss.SSS&#125;) %contextName [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="name">pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">encoder</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">topic</span>&gt;</span>oauth2-auth-server<span class="tag">&lt;/<span class="name">topic</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 我们不关心如何对日志消息进行分区 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">keyingStrategy</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.keying.NoKeyKeyingStrategy&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 使用异步传递。 日志记录不会阻止应用程序线程 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">deliveryStrategy</span> <span class="attr">class</span>=<span class="string">&quot;com.github.danielwegener.logback.kafka.delivery.AsynchronousDeliveryStrategy&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 每个&lt;producerConfig&gt;转换为常规kafka-client配置（格式：key = value） --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 生产者配置记录在这里：https://kafka.apache.org/documentation.html#newproducerconfigs --&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- bootstrap.servers是唯一必需的 producerConfig --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>bootstrap.servers=192.168.213.13:9092,192.168.213.14:9092,192.168.213.21:9092<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 不用等待代理对批的接收进行打包。  --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>acks=0<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 等待最多1000毫秒并收集日志消息，然后再批量发送 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>linger.ms=1000<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 即使生产者缓冲区运行已满，也不要阻止应用程序而是开始丢弃消息 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>max.block.ms=0<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 定义用于标识kafka代理的客户端ID --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">producerConfig</span>&gt;</span>client.id=$&#123;HOSTNAME&#125;-$&#123;CONTEXT_NAME&#125;-logback-relaxed<span class="tag">&lt;/<span class="name">producerConfig</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 如果kafka不可用，这是后备appender。 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;file&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">&lt;!--输出到文件--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">appender</span> <span class="attr">name</span>=<span class="string">&quot;file&quot;</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.core.rolling.RollingFileAppender&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">rollingPolicy</span> <span class="attr">class</span>=<span class="string">&quot;ch.qos.logback.core.rolling.TimeBasedRollingPolicy&quot;</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--日志文件输出的文件名--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">FileNamePattern</span>&gt;</span>$&#123;LOG_HOME&#125;/oauth2-auth-server.log.%d&#123;yyyy-MM-dd&#125;.log<span class="tag">&lt;/<span class="name">FileNamePattern</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--日志文件保留天数--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">MaxHistory</span>&gt;</span>30<span class="tag">&lt;/<span class="name">MaxHistory</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">rollingPolicy</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">encoder</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--格式化输出：%d表示日期，%thread表示线程名，%-5level：级别从左显示5个字符宽度%msg：日志消息，%n是换行符--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">pattern</span>&gt;</span>%-12(%d&#123;yyyy-MM-dd HH:mm:ss.SSS&#125;) %contextName [%thread] %-5level %logger&#123;36&#125; - %msg%n<span class="tag">&lt;/<span class="name">pattern</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">charset</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">charset</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">encoder</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">appender</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">root</span> <span class="attr">level</span>=<span class="string">&quot;info&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;console&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">appender-ref</span> <span class="attr">ref</span>=<span class="string">&quot;kafka&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">root</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="2-Kafka-与-Logstash-的集成"><a href="#2-Kafka-与-Logstash-的集成" class="headerlink" title="2. Kafka 与 Logstash 的集成"></a>2. Kafka 与 Logstash 的集成</h2><p>logstash 与 Kafka 的简单配置</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">input</span> &#123;</span><br><span class="line">     <span class="string">kafka</span> &#123;</span><br><span class="line">        <span class="string">topics</span> <span class="string">=&gt;</span> <span class="string">&quot;applog&quot;</span></span><br><span class="line">        <span class="string">bootstrap_servers</span> <span class="string">=&gt;</span> <span class="string">&quot;Kafka服务器IP:9092,Kafka服务器IP:9092&quot;</span></span><br><span class="line">        <span class="string">codec</span> <span class="string">=&gt;</span> <span class="string">&quot;json&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="string">filter</span> &#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="string">output</span> &#123;</span><br><span class="line">  <span class="string">//控制台输入</span></span><br><span class="line">  <span class="string">stdout</span> &#123;  <span class="string">codec</span> <span class="string">=&gt;</span> <span class="string">rubydebug</span> &#125;</span><br><span class="line">  <span class="string">elasticsearch</span> &#123;</span><br><span class="line">    <span class="string">hosts</span> <span class="string">=&gt;</span> [ <span class="string">&quot;elasticsearch服务器IP:9200&quot;</span> ]</span><br><span class="line">    <span class="string">index</span> <span class="string">=&gt;</span> <span class="string">&quot;kafka&quot;</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>启动 logstash：</p>
<p><code>.\bin\logstash -f .\conf\logstash-kaka.conf</code></p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E5%A6%82%E4%BD%95%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/26/Spring-Security-Oauth2%E5%A6%82%E4%BD%95%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%88%E6%9D%83%E6%A8%A1%E5%BC%8F/" class="post-title-link" itemprop="url">Spring-Security-Oauth2如何增加自定义授权模式</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 11:17:29" itemprop="dateCreated datePublished" datetime="2019-06-26T11:17:29+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/oauth2/" itemprop="url" rel="index"><span itemprop="name">oauth2</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>在 oauth2 的授权模式中有4种：</p>
<ul>
<li>授权码模式</li>
<li>隐式授权模式</li>
<li>密码模式</li>
<li>客户端模式</li>
</ul>
<p>但如果我们想要增加一个自定义的授权模式，又该怎么做呢？</p>
<p>相关的源码是这样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CompositeTokenGranter</span> <span class="keyword">implements</span> <span class="title">TokenGranter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> List&lt;TokenGranter&gt; tokenGranters;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">CompositeTokenGranter</span><span class="params">(List&lt;TokenGranter&gt; tokenGranters)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;(tokenGranters);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//四种授权模式+刷新令牌的模式根据grant_type判断</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">for</span> (TokenGranter granter : tokenGranters) &#123;</span><br><span class="line">			OAuth2AccessToken grant = granter.grant(grantType, tokenRequest);</span><br><span class="line">			<span class="keyword">if</span> (grant!=<span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span> grant;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addTokenGranter</span><span class="params">(TokenGranter tokenGranter)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Token granter is null&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		tokenGranters.add(tokenGranter);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>oauth2 端点配置类部分源码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthorizationServerEndpointsConfigurer</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> AuthorizationServerEndpointsConfigurer <span class="title">tokenGranter</span><span class="params">(TokenGranter tokenGranter)</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">this</span>.tokenGranter = tokenGranter;</span><br><span class="line">    	<span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 默认的四种授权模式+刷新令牌的模式的配置</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> TokenGranter <span class="title">tokenGranter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	<span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">    		tokenGranter = <span class="keyword">new</span> TokenGranter() &#123;</span><br><span class="line">    			<span class="keyword">private</span> CompositeTokenGranter delegate;</span><br><span class="line">    </span><br><span class="line">    			<span class="meta">@Override</span></span><br><span class="line">    			<span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">    				<span class="keyword">if</span> (delegate == <span class="keyword">null</span>) &#123;</span><br><span class="line">    					delegate = <span class="keyword">new</span> CompositeTokenGranter(getDefaultTokenGranters());</span><br><span class="line">    				&#125;</span><br><span class="line">    				<span class="keyword">return</span> delegate.grant(grantType, tokenRequest);</span><br><span class="line">    			&#125;</span><br><span class="line">    		&#125;;</span><br><span class="line">    	&#125;</span><br><span class="line">    	<span class="keyword">return</span> tokenGranter;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 默认的四种授权模式+刷新令牌的模式的配置</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;TokenGranter&gt; <span class="title">getDefaultTokenGranters</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    	ClientDetailsService clientDetails = clientDetailsService();</span><br><span class="line">    	AuthorizationServerTokenServices tokenServices = tokenServices();</span><br><span class="line">    	AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();</span><br><span class="line">    	OAuth2RequestFactory requestFactory = requestFactory();</span><br><span class="line">    	</span><br><span class="line">    	List&lt;TokenGranter&gt; tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;();</span><br><span class="line">    	<span class="comment">// 添加授权码模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetails,</span><br><span class="line">    			requestFactory));</span><br><span class="line">    	<span class="comment">// 添加刷新令牌的模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> RefreshTokenGranter(tokenServices, clientDetails, requestFactory));</span><br><span class="line">    	<span class="comment">// 添加隐式授权模式</span></span><br><span class="line">    	ImplicitTokenGranter implicit = <span class="keyword">new</span> ImplicitTokenGranter(tokenServices, clientDetails, requestFactory);</span><br><span class="line">    	tokenGranters.add(implicit);</span><br><span class="line">    	<span class="comment">// 添加客户端模式</span></span><br><span class="line">    	tokenGranters.add(<span class="keyword">new</span> ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));</span><br><span class="line">    	<span class="keyword">if</span> (authenticationManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">    	    <span class="comment">// 添加密码模式</span></span><br><span class="line">    		tokenGranters.add(<span class="keyword">new</span> ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices,</span><br><span class="line">    				clientDetails, requestFactory));</span><br><span class="line">    	&#125;</span><br><span class="line">    	</span><br><span class="line">    	<span class="comment">// 可以复制相关代码，然后这里添加自定义的授权模式</span></span><br><span class="line">    	</span><br><span class="line">    	<span class="keyword">return</span> tokenGranters;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到这里就可以发现 spring 已经把默认的四种授权模式+刷新令牌的模式的配置在代码中写死了!</p>
<p>那又如何添加自定义的授权模式呢？</p>
<p>我的思路是这样的：</p>
<p>直接把这部分的代码复制，在其中添加自定义的授权模式。</p>
<p>我直接把密码模式复制，将其中的 <code>GRANT_TYPE</code> 的值改为 <code>sms_code</code>,然后使用 <code>/oauth/token?grant_type=sms_code&amp;scope=read&amp;username=user&amp;password=123456</code> 来验证结果。</p>
<h2 id="自定义授权模式：SmsCodeTokenGranter"><a href="#自定义授权模式：SmsCodeTokenGranter" class="headerlink" title="自定义授权模式：SmsCodeTokenGranter"></a>自定义授权模式：SmsCodeTokenGranter</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsCodeTokenGranter</span> <span class="keyword">extends</span> <span class="title">AbstractTokenGranter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 仅仅复制了 ResourceOwnerPasswordTokenGranter，只是改变了 GRANT_TYPE 的值，来验证自定义授权模式的可行性</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String GRANT_TYPE = <span class="string">&quot;sms_code&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AuthenticationManager authenticationManager;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsCodeTokenGranter</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthenticationManager authenticationManager,</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthorizationServerTokenServices tokenServices,</span></span></span><br><span class="line"><span class="function"><span class="params">            ClientDetailsService clientDetailsService,</span></span></span><br><span class="line"><span class="function"><span class="params">            OAuth2RequestFactory requestFactory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="title">SmsCodeTokenGranter</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthenticationManager authenticationManager,</span></span></span><br><span class="line"><span class="function"><span class="params">            AuthorizationServerTokenServices tokenServices,</span></span></span><br><span class="line"><span class="function"><span class="params">            ClientDetailsService clientDetailsService,</span></span></span><br><span class="line"><span class="function"><span class="params">            OAuth2RequestFactory requestFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">            String grantType)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(tokenServices, clientDetailsService, requestFactory, grantType);</span><br><span class="line">        <span class="keyword">this</span>.authenticationManager = authenticationManager;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> OAuth2Authentication <span class="title">getOAuth2Authentication</span><span class="params">(ClientDetails client, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">        Map&lt;String, String&gt; parameters = <span class="keyword">new</span> LinkedHashMap&lt;String, String&gt;(tokenRequest.getRequestParameters());</span><br><span class="line">        String username = parameters.get(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        String password = parameters.get(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">        <span class="comment">// Protect from downstream leaks of password</span></span><br><span class="line">        parameters.remove(<span class="string">&quot;password&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Authentication userAuth = <span class="keyword">new</span> UsernamePasswordAuthenticationToken(username, password);</span><br><span class="line">        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            userAuth = authenticationManager.authenticate(userAuth);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (AccountStatusException ase) &#123;</span><br><span class="line">            <span class="comment">//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(ase.getMessage());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (BadCredentialsException e) &#123;</span><br><span class="line">            <span class="comment">// If the username/password are wrong the spec says we should send 400/invalid grant</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (userAuth == <span class="keyword">null</span> || !userAuth.isAuthenticated()) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InvalidGrantException(<span class="string">&quot;Could not authenticate user: &quot;</span> + username);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> OAuth2Authentication(storedOAuth2Request, userAuth);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="授权模式配置类：TokenGranterConfig"><a href="#授权模式配置类：TokenGranterConfig" class="headerlink" title="授权模式配置类：TokenGranterConfig"></a>授权模式配置类：TokenGranterConfig</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile(&quot;inMemory&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TokenGranterConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ClientDetailsService clientDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailsService userDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationManager authenticationManager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TokenStore tokenStore;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    TokenEnhancer tokenEnhancer;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AuthorizationCodeServices authorizationCodeServices;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> reuseRefreshToken = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> AuthorizationServerTokenServices tokenServices;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 授权模式</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TokenGranter <span class="title">tokenGranter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (tokenGranter == <span class="keyword">null</span>) &#123;</span><br><span class="line">            tokenGranter = <span class="keyword">new</span> TokenGranter() &#123;</span><br><span class="line">                <span class="keyword">private</span> CompositeTokenGranter delegate;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">grant</span><span class="params">(String grantType, TokenRequest tokenRequest)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span> (delegate == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        delegate = <span class="keyword">new</span> CompositeTokenGranter(getDefaultTokenGranters());</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> delegate.grant(grantType, tokenRequest);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> tokenGranter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 程序支持的授权类型</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;TokenGranter&gt; <span class="title">getDefaultTokenGranters</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        AuthorizationServerTokenServices tokenServices = tokenServices();</span><br><span class="line">        AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();</span><br><span class="line">        OAuth2RequestFactory requestFactory = requestFactory();</span><br><span class="line"></span><br><span class="line">        List&lt;TokenGranter&gt; tokenGranters = <span class="keyword">new</span> ArrayList&lt;TokenGranter&gt;();</span><br><span class="line">        <span class="comment">// 添加授权码模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加刷新令牌的模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加隐士授权模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="comment">// 添加客户端模式</span></span><br><span class="line">        tokenGranters.add(<span class="keyword">new</span> ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        <span class="keyword">if</span> (authenticationManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 添加密码模式</span></span><br><span class="line">            tokenGranters.add(<span class="keyword">new</span> ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">            <span class="comment">// 添加自定义授权模式（实际是密码模式的复制）</span></span><br><span class="line">            tokenGranters.add(<span class="keyword">new</span> SmsCodeTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> tokenGranters;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * TokenServices</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> AuthorizationServerTokenServices <span class="title">tokenServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (tokenServices != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> tokenServices;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.tokenServices = createDefaultTokenServices();</span><br><span class="line">        <span class="keyword">return</span> tokenServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 授权码API</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> AuthorizationCodeServices <span class="title">authorizationCodeServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (authorizationCodeServices == <span class="keyword">null</span>) &#123;</span><br><span class="line">            authorizationCodeServices = <span class="keyword">new</span> InMemoryAuthorizationCodeServices();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> authorizationCodeServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * OAuth2RequestFactory的默认实现，它初始化参数映射中的字段，</span></span><br><span class="line"><span class="comment">     * 验证授权类型(grant_type)和范围(scope)，并使用客户端的默认值填充范围(scope)（如果缺少这些值）。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> OAuth2RequestFactory <span class="title">requestFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DefaultOAuth2RequestFactory(clientDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 默认 TokenService</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> DefaultTokenServices <span class="title">createDefaultTokenServices</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        DefaultTokenServices tokenServices = <span class="keyword">new</span> DefaultTokenServices();</span><br><span class="line">        tokenServices.setTokenStore(tokenStore);</span><br><span class="line">        tokenServices.setSupportRefreshToken(<span class="keyword">true</span>);</span><br><span class="line">        tokenServices.setReuseRefreshToken(reuseRefreshToken);</span><br><span class="line">        tokenServices.setClientDetailsService(clientDetailsService);</span><br><span class="line">        tokenServices.setTokenEnhancer(tokenEnhancer);</span><br><span class="line">        addUserDetailsService(tokenServices, <span class="keyword">this</span>.userDetailsService);</span><br><span class="line">        <span class="keyword">return</span> tokenServices;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 添加预身份验证</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> tokenServices</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> userDetailsService</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addUserDetailsService</span><span class="params">(DefaultTokenServices tokenServices, UserDetailsService userDetailsService)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (userDetailsService != <span class="keyword">null</span>) &#123;</span><br><span class="line">            PreAuthenticatedAuthenticationProvider provider = <span class="keyword">new</span> PreAuthenticatedAuthenticationProvider();</span><br><span class="line">            provider.setPreAuthenticatedUserDetailsService(<span class="keyword">new</span> UserDetailsByNameServiceWrapper&lt;PreAuthenticatedAuthenticationToken&gt;(userDetailsService));</span><br><span class="line">            tokenServices.setAuthenticationManager(<span class="keyword">new</span> ProviderManager(Arrays.&lt;AuthenticationProvider&gt;asList(provider)));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="授权认证服务端点配置"><a href="#授权认证服务端点配置" class="headerlink" title="授权认证服务端点配置"></a>授权认证服务端点配置</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.config.inmemory;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/8</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@EnableAuthorizationServer</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Profile(&quot;inMemory&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthorizationServerConfigInMemory</span> <span class="keyword">extends</span> <span class="title">AuthorizationServerConfigurerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> TokenGranter tokenGranter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 认证服务器节点配置</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> endpoints</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        endpoints</span><br><span class="line">                .tokenGranter(tokenGranter) <span class="comment">// 四种授权模式+刷新令牌的模式+自定义授权模式</span></span><br><span class="line">                .tokenStore(tokenStore)</span><br><span class="line">                .approvalStore(approvalStore)</span><br><span class="line">                .userDetailsService(userDetailsService)</span><br><span class="line">                .authenticationManager(authenticationManager)</span><br><span class="line">                .setClientDetailsService(clientDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="演示效果"><a href="#演示效果" class="headerlink" title="演示效果"></a>演示效果</h2><p><img src="https://img-blog.csdnimg.cn/20190618152045144.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">POST http://localhost:8080/oauth/token?grant_type=sms_code&amp;scope=read&amp;username=user&amp;password=123456</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">200</span> </span><br><span class="line"><span class="attribute">X-Application-Context</span><span class="punctuation">: </span>application:inMemory</span><br><span class="line"><span class="attribute">Cache-Control</span><span class="punctuation">: </span>no-store</span><br><span class="line"><span class="attribute">Pragma</span><span class="punctuation">: </span>no-cache</span><br><span class="line"><span class="attribute">X-Content-Type-Options</span><span class="punctuation">: </span>nosniff</span><br><span class="line"><span class="attribute">X-XSS-Protection</span><span class="punctuation">: </span>1; mode=block</span><br><span class="line"><span class="attribute">X-Frame-Options</span><span class="punctuation">: </span>DENY</span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>application/json;charset=UTF-8</span><br><span class="line"><span class="attribute">Transfer-Encoding</span><span class="punctuation">: </span>chunked</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Tue, 18 Jun 2019 07:13:12 GMT</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  &quot;access_token&quot;: &quot;19f2e44a-6c9a-45c4-be7e-0aada6a0a9e6&quot;,</span><br><span class="line">  &quot;token_type&quot;: &quot;bearer&quot;,</span><br><span class="line">  &quot;refresh_token&quot;: &quot;f59336a8-03c4-4c85-bc31-16c6d80f1381&quot;,</span><br><span class="line">  &quot;expires_in&quot;: 359,</span><br><span class="line">  &quot;scope&quot;: &quot;read&quot;,</span><br><span class="line">  &quot;organization&quot;: &quot;userWqTI&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Response code: 200; Time: 335ms; Content length: 190 bytes</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E6%B7%BB%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E8%BF%87%E6%BB%A4%E5%99%A8%E5%92%8Coauth2%E8%AE%A4%E8%AF%81%E5%90%8EAPI%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/26/Spring-Security-Oauth2%E6%B7%BB%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E8%BF%87%E6%BB%A4%E5%99%A8%E5%92%8Coauth2%E8%AE%A4%E8%AF%81%E5%90%8EAPI%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6/" class="post-title-link" itemprop="url">Spring-Security-Oauth2添加自定义过滤器和oauth2认证后API权限控制</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 11:16:13" itemprop="dateCreated datePublished" datetime="2019-06-26T11:16:13+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/oauth2/" itemprop="url" rel="index"><span itemprop="name">oauth2</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>在搭建完 spring-security-oauth2 整个微服务框架后，来了一个需求：</p>
<blockquote>
<p>每个微服务都需要对访问进行鉴权，每个微服务应用都需要明确当前访问用户和他的权限。</p>
</blockquote>
<p>auth 系统的主要功能是授权认证和鉴权。</p>
<p>授权认证已经完成，那么如何对用户的访问进行鉴权呢？</p>
<p>首先需要明确什么时候发生鉴权？</p>
<p>鉴权发生在用户已经认证后携带了 access_token 信息但还没用访问到目标资源的时候。</p>
<p>知道了鉴权发生的时间，需要明白怎么鉴权？</p>
<p>我的想法是添加一个用于鉴权的过滤器，Spring Security 默认的过滤器链(<a target="_blank" rel="noopener" href="https://docs.spring.io/spring-security/site/docs/5.0.0.M1/reference/htmlsingle/#ns-custom-filters">官网</a>)：</p>
<table>
<thead>
<tr>
<th>别名</th>
<th>类名称</th>
<th>Namespace Element or Attribute</th>
</tr>
</thead>
<tbody><tr>
<td>CHANNEL_FILTER</td>
<td>ChannelProcessingFilter</td>
<td>http/intercept-url@requires-channel</td>
</tr>
<tr>
<td>SECURITY_CONTEXT_FILTER</td>
<td>SecurityContextPersistenceFilter</td>
<td>http</td>
</tr>
<tr>
<td>CONCURRENT_SESSION_FILTER</td>
<td>ConcurrentSessionFilter</td>
<td>session-management/concurrency-control</td>
</tr>
<tr>
<td>HEADERS_FILTER</td>
<td>HeaderWriterFilter</td>
<td>http/headers</td>
</tr>
<tr>
<td>CSRF_FILTER</td>
<td>CsrfFilter</td>
<td>http/csrf</td>
</tr>
<tr>
<td>LOGOUT_FILTER</td>
<td>LogoutFilter</td>
<td>http/logout</td>
</tr>
<tr>
<td>X509_FILTER</td>
<td>X509AuthenticationFilter</td>
<td>http/x509</td>
</tr>
<tr>
<td>PRE_AUTH_FILTER</td>
<td>AbstractPreAuthenticatedProcessingFilter( Subclasses)</td>
<td>N/A</td>
</tr>
<tr>
<td>CAS_FILTER</td>
<td>CasAuthenticationFilter    N/A</td>
<td></td>
</tr>
<tr>
<td>FORM_LOGIN_FILTER</td>
<td>UsernamePasswordAuthenticationFilter</td>
<td>http/form-login</td>
</tr>
<tr>
<td>BASIC_AUTH_FILTER</td>
<td>BasicAuthenticationFilter</td>
<td>http/http-basic</td>
</tr>
<tr>
<td>SERVLET_API_SUPPORT_FILTER</td>
<td>SecurityContextHolderAwareRequestFilter</td>
<td>http/@servlet-api-provision</td>
</tr>
<tr>
<td>JAAS_API_SUPPORT_FILTER</td>
<td>JaasApiIntegrationFilter</td>
<td>http/@jaas-api-provision</td>
</tr>
<tr>
<td>REMEMBER_ME_FILTER</td>
<td>RememberMeAuthenticationFilter</td>
<td>http/remember-me</td>
</tr>
<tr>
<td>ANONYMOUS_FILTER</td>
<td>AnonymousAuthenticationFilter</td>
<td>http/anonymous</td>
</tr>
<tr>
<td>SESSION_MANAGEMENT_FILTER</td>
<td>SessionManagementFilter</td>
<td>session-management</td>
</tr>
<tr>
<td>EXCEPTION_TRANSLATION_FILTER</td>
<td>ExceptionTranslationFilter</td>
<td>http</td>
</tr>
<tr>
<td>FILTER_SECURITY_INTERCEPTOR</td>
<td>FilterSecurityInterceptor</td>
<td>http</td>
</tr>
<tr>
<td>SWITCH_USER_FILTER</td>
<td>SwitchUserFilter</td>
<td>N/A</td>
</tr>
</tbody></table>
<blockquote>
<p>过滤器顺序从上到下</p>
</blockquote>
<p><code>FilterSecurityInterceptor</code> 是 filterchain 中比较复杂，也是比较核心的过滤器，主要负责web应用安全授权的工作。</p>
<p>我想添加的过滤器是添加在 <code>FilterSecurityInterceptor</code> 之后。</p>
<p><code>Oauth2FilterSecurityInterceptor</code> 是模仿 FilterSecurityInterceptor 实现，继承 AbstractSecurityInterceptor 和实现 Filter 接口。</p>
<p>整个过程需要依赖 AuthenticationManager、AccessDecisionManager 和 FilterInvocationSecurityMetadataSource。</p>
<ul>
<li>AuthenticationManager是认证管理器，实现用户认证的入口；</li>
<li>AccessDecisionManager是访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源；</li>
<li>FilterInvocationSecurityMetadataSource是资源源数据定义，即定义某一资源可以被哪些角色访问。</li>
</ul>
<h2 id="自定义鉴权过滤器-Oauth2FilterSecurityInterceptor-的实现"><a href="#自定义鉴权过滤器-Oauth2FilterSecurityInterceptor-的实现" class="headerlink" title="自定义鉴权过滤器 Oauth2FilterSecurityInterceptor 的实现"></a>自定义鉴权过滤器 <code>Oauth2FilterSecurityInterceptor</code> 的实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.authorization;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.SecurityMetadataSource;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.intercept.AbstractSecurityInterceptor;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.intercept.InterceptorStatusToken;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.FilterInvocation;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.*;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 比较核心的过滤器: 主要负责web应用鉴权的工作。</span></span><br><span class="line"><span class="comment"> * 需要依赖:</span></span><br><span class="line"><span class="comment"> * - AuthenticationManager:认证管理器，实现用户认证的入口;</span></span><br><span class="line"><span class="comment"> * - AccessDecisionManager:访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源;</span></span><br><span class="line"><span class="comment"> * - FilterInvocationSecurityMetadataSource:资源源数据定义，即定义某一资源可以被哪些角色访问.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/6/17</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Oauth2FilterSecurityInterceptor</span> <span class="keyword">extends</span> <span class="title">AbstractSecurityInterceptor</span> <span class="keyword">implements</span> <span class="title">Filter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Oauth2FilterInvocationSecurityMetadataSource securityMetadataSource;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (log.isInfoEnabled()) &#123;</span><br><span class="line">            log.info(<span class="string">&quot;Oauth2FilterSecurityInterceptor init&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (log.isInfoEnabled()) &#123;</span><br><span class="line">            log.info(<span class="string">&quot;Oauth2FilterSecurityInterceptor doFilter&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        FilterInvocation filterInvocation = <span class="keyword">new</span> FilterInvocation(request, response, chain);</span><br><span class="line">        invoke(filterInvocation);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invoke</span><span class="params">(FilterInvocation filterInvocation)</span> <span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">        <span class="comment">// filterInvocation里面有一个被拦截的url</span></span><br><span class="line">        <span class="comment">// 里面调用 Oauth2AccessDecisionManager 的 getAttributes(Object object) 这个方法获取 filterInvocation 对应的所有权限</span></span><br><span class="line">        <span class="comment">// 再调用 Oauth2AccessDecisionManager 的 decide方法来校验用户的权限是否足够</span></span><br><span class="line">        InterceptorStatusToken interceptorStatusToken = <span class="keyword">super</span>.beforeInvocation(filterInvocation);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 执行下一个拦截器</span></span><br><span class="line">            filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">super</span>.afterInvocation(interceptorStatusToken, <span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Class&lt;?&gt; getSecureObjectClass() &#123;</span><br><span class="line">        <span class="keyword">return</span> FilterInvocation.class;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 资源源数据定义，设置为自定义的 SecureResourceFilterInvocationDefinitionSource</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SecurityMetadataSource <span class="title">obtainSecurityMetadataSource</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> securityMetadataSource;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setOauth2AccessDecisionManager</span><span class="params">(Oauth2AccessDecisionManager accessDecisionManager)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.setAccessDecisionManager(accessDecisionManager);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAuthenticationManager</span><span class="params">(AuthenticationManager authenticationManager)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.setAuthenticationManager(authenticationManager);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setSecurityMetadataSource</span><span class="params">(Oauth2FilterInvocationSecurityMetadataSource securityMetadataSource)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.securityMetadataSource = securityMetadataSource;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看下父类的 <code>beforeInvocation</code> 方法，其中省略了一些不重要的代码片段:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractSecurityInterceptor</span> <span class="keyword">implements</span> <span class="title">InitializingBean</span>, <span class="title">ApplicationEventPublisherAware</span>, <span class="title">MessageSourceAware</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">protected</span> InterceptorStatusToken <span class="title">beforeInvocation</span><span class="params">(Object object)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 代码省略</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 根据 SecurityMetadataSource 获取配置的权限属性</span></span><br><span class="line">		Collection&lt;ConfigAttribute&gt; attributes = <span class="keyword">this</span>.obtainSecurityMetadataSource()</span><br><span class="line">				.getAttributes(object);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 代码省略</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 判断是否需要对认证实体重新认证，默认为否</span></span><br><span class="line">		Authentication authenticated = authenticateIfRequired();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// Attempt authorization</span></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 决策管理器开始决定是否授权，如果授权失败，直接抛出 AccessDeniedException</span></span><br><span class="line">	        <span class="keyword">this</span>.accessDecisionManager.decide(authenticated, object, attributes);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (AccessDeniedException accessDeniedException) &#123;</span><br><span class="line">			publishEvent(<span class="keyword">new</span> AuthorizationFailureEvent(object, attributes, authenticated,</span><br><span class="line">					accessDeniedException));</span><br><span class="line"></span><br><span class="line">			<span class="keyword">throw</span> accessDeniedException;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 代码省略</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="自定义资源源数据定义-Oauth2FilterInvocationSecurityMetadataSource"><a href="#自定义资源源数据定义-Oauth2FilterInvocationSecurityMetadataSource" class="headerlink" title="自定义资源源数据定义 Oauth2FilterInvocationSecurityMetadataSource"></a>自定义资源源数据定义 Oauth2FilterInvocationSecurityMetadataSource</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.authorization;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fengxuechao.examples.auth.service.UserRolePermissionService;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.InitializingBean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.ConfigAttribute;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.SecurityConfig;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.FilterInvocation;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Collection;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 资源源数据定义，即定义某一资源可以被哪些角色访问</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/6/14</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Oauth2FilterInvocationSecurityMetadataSource</span> <span class="keyword">implements</span> <span class="title">FilterInvocationSecurityMetadataSource</span>, <span class="title">InitializingBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> UserRolePermissionService service;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Oauth2FilterInvocationSecurityMetadataSource</span><span class="params">(UserRolePermissionService service)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.service = service;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Collection&lt;ConfigAttribute&gt; <span class="title">getAttributes</span><span class="params">(Object object)</span> <span class="keyword">throws</span> IllegalArgumentException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;/user/profile&quot;</span>.equals(((FilterInvocation) object).getRequestUrl())) &#123;</span><br><span class="line">            <span class="comment">// [/user/profile] 不需要鉴权</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/*if (object instanceof FilterInvocation) &#123;</span></span><br><span class="line"><span class="comment">            FilterInvocation fi = (FilterInvocation) object;</span></span><br><span class="line"><span class="comment">            String requestUrl = fi.getRequestUrl();</span></span><br><span class="line"><span class="comment">            // 返回请求所需的权限</span></span><br><span class="line"><span class="comment">            List&lt;Role&gt; roleList = service.findRoleListByPermissionUrl(requestUrl);</span></span><br><span class="line"><span class="comment">            String[] roleArray = new String[roleList.size()];</span></span><br><span class="line"><span class="comment">            roleArray = roleList.toArray(roleArray);</span></span><br><span class="line"><span class="comment">            return SecurityConfig.createList(roleArray);</span></span><br><span class="line"><span class="comment">        &#125;</span></span><br><span class="line"><span class="comment">        return Collections.EMPTY_LIST;*/</span></span><br><span class="line">        <span class="keyword">return</span> SecurityConfig.createList(<span class="string">&quot;ROLE_ADMIN&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Collection&lt;ConfigAttribute&gt; <span class="title">getAllConfigAttributes</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了调试的方便，直接定死任何访问请求都需要管理员权限(/user/profile 除外)，调试通过后，再往里面添加业务逻辑代码。</p>
<h2 id="自定义决策管理器-Oauth2AccessDecisionManager"><a href="#自定义决策管理器-Oauth2AccessDecisionManager" class="headerlink" title="自定义决策管理器 Oauth2AccessDecisionManager"></a>自定义决策管理器 Oauth2AccessDecisionManager</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.authorization;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.AccessDecisionManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.AccessDeniedException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.access.ConfigAttribute;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.InsufficientAuthenticationException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.Authentication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.GrantedAuthority;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.FilterInvocation;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Collection;</span><br><span class="line"><span class="keyword">import</span> java.util.Iterator;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 访问决策器，决定某个用户具有的角色，是否有足够的权限去访问某个资源</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/6/14</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Oauth2AccessDecisionManager</span> <span class="keyword">implements</span> <span class="title">AccessDecisionManager</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> authentication   用户凭证</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> resource         资源 URL</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> configAttributes 资源 URL 所需要的权限</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> AccessDeniedException               资源拒绝访问</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> InsufficientAuthenticationException 用户凭证不符</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">decide</span><span class="params">(Authentication authentication, Object resource, Collection&lt;ConfigAttribute&gt; configAttributes)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> AccessDeniedException, InsufficientAuthenticationException </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;[决策管理器]:开始判断请求 &#123;&#125; 需要的权限&quot;</span>, ((FilterInvocation) resource).getRequestUrl());</span><br><span class="line">        <span class="keyword">if</span> (configAttributes == <span class="keyword">null</span> || configAttributes.isEmpty()) &#123;</span><br><span class="line">            log.info(<span class="string">&quot;[决策管理器]:请求 &#123;&#125; 无需权限&quot;</span>, ((FilterInvocation) resource).getRequestUrl());</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        log.info(<span class="string">&quot;[决策管理器]:请求 &#123;&#125; 需要的权限 - &#123;&#125;&quot;</span>, ((FilterInvocation) resource).getRequestUrl(), configAttributes);</span><br><span class="line">        <span class="comment">// 判断用户所拥有的权限，是否符合对应的Url权限，用户权限是实现 UserDetailsService#loadUserByUsername 返回用户所对应的权限</span></span><br><span class="line">        Iterator&lt;ConfigAttribute&gt; ite = configAttributes.iterator();</span><br><span class="line">        log.info(<span class="string">&quot;[决策管理器]:用户 &#123;&#125; 拥有的权限 - &#123;&#125;&quot;</span>, authentication.getName(), authentication.getAuthorities());</span><br><span class="line">        <span class="keyword">while</span> (ite.hasNext()) &#123;</span><br><span class="line">            ConfigAttribute neededAuthority = ite.next();</span><br><span class="line">            String neededAuthorityStr = neededAuthority.getAttribute();</span><br><span class="line">            <span class="keyword">for</span> (GrantedAuthority existingAuthority : authentication.getAuthorities()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (neededAuthorityStr.equals(existingAuthority.getAuthority())) &#123;</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        log.info(<span class="string">&quot;[决策管理器]:用户 &#123;&#125; 没有访问资源 &#123;&#125; 的权限!&quot;</span>, authentication.getName(), ((FilterInvocation) resource).getRequestUrl());</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> AccessDeniedException(<span class="string">&quot;权限不足!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(ConfigAttribute attribute)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 是否支持 FilterInvocationSecurityMetadataSource 需要将这里的false改为true</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> clazz</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Class&lt;?&gt; clazz)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="配置自定义鉴权过滤器-Oauth2FilterSecurityInterceptor-在-Spring-Security-过滤器链中的位置"><a href="#配置自定义鉴权过滤器-Oauth2FilterSecurityInterceptor-在-Spring-Security-过滤器链中的位置" class="headerlink" title="配置自定义鉴权过滤器 Oauth2FilterSecurityInterceptor 在 Spring Security 过滤器链中的位置"></a>配置自定义鉴权过滤器 <code>Oauth2FilterSecurityInterceptor</code> 在 Spring Security 过滤器链中的位置</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.fengxuechao.examples.auth.authorization.Oauth2AccessDecisionManager;</span><br><span class="line"><span class="keyword">import</span> com.fengxuechao.examples.auth.authorization.Oauth2FilterInvocationSecurityMetadataSource;</span><br><span class="line"><span class="keyword">import</span> com.fengxuechao.examples.auth.authorization.Oauth2FilterSecurityInterceptor;</span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.config.annotation.web.builders.HttpSecurity;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.web.access.intercept.FilterSecurityInterceptor;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/8</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@EnableResourceServer</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ResourceServerConfig</span> <span class="keyword">extends</span> <span class="title">ResourceServerConfigurerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    AuthenticationManager manager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Oauth2AccessDecisionManager accessDecisionManager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Oauth2FilterInvocationSecurityMetadataSource securityMetadataSource;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        http.authorizeRequests().anyRequest().authenticated();</span><br><span class="line">        http.addFilterAfter(createApiAuthenticationFilter(), FilterSecurityInterceptor.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * API权限控制</span></span><br><span class="line"><span class="comment">     * 过滤器优先度在 FilterSecurityInterceptor 之后</span></span><br><span class="line"><span class="comment">     * spring-security 的默认过滤器列表见 https://docs.spring.io/spring-security/site/docs/5.0.0.M1/reference/htmlsingle/#ns-custom-filters</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Oauth2FilterSecurityInterceptor <span class="title">createApiAuthenticationFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Oauth2FilterSecurityInterceptor interceptor = <span class="keyword">new</span> Oauth2FilterSecurityInterceptor();</span><br><span class="line">        interceptor.setAuthenticationManager(manager);</span><br><span class="line">        interceptor.setAccessDecisionManager(accessDecisionManager);</span><br><span class="line">        interceptor.setSecurityMetadataSource(securityMetadataSource);</span><br><span class="line">        <span class="keyword">return</span> interceptor;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="配置用户权限"><a href="#配置用户权限" class="headerlink" title="配置用户权限"></a>配置用户权限</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.userdetails;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.authority.AuthorityUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.User;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UserDetailsService;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.core.userdetails.UsernameNotFoundException;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/15</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDetailsServiceImpl</span> <span class="keyword">implements</span> <span class="title">UserDetailsService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserDetails <span class="title">loadUserByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> UsernameNotFoundException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> User(username, <span class="string">&quot;123456&quot;</span>, AuthorityUtils.commaSeparatedStringToAuthorityList(<span class="string">&quot;ROLE_USER&quot;</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="演示结果"><a href="#演示结果" class="headerlink" title="演示结果"></a>演示结果</h2><h3 id="用户拥有资源所需权限"><a href="#用户拥有资源所需权限" class="headerlink" title="用户拥有资源所需权限"></a>用户拥有资源所需权限</h3><p>请求：</p>
<figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">GET http://localhost:8080/order/1</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">200</span> </span><br><span class="line"><span class="attribute">X-Application-Context</span><span class="punctuation">: </span>application:inMemory</span><br><span class="line"><span class="attribute">X-Content-Type-Options</span><span class="punctuation">: </span>nosniff</span><br><span class="line"><span class="attribute">X-XSS-Protection</span><span class="punctuation">: </span>1; mode=block</span><br><span class="line"><span class="attribute">Cache-Control</span><span class="punctuation">: </span>no-cache, no-store, max-age=0, must-revalidate</span><br><span class="line"><span class="attribute">Pragma</span><span class="punctuation">: </span>no-cache</span><br><span class="line"><span class="attribute">Expires</span><span class="punctuation">: </span>0</span><br><span class="line"><span class="attribute">X-Frame-Options</span><span class="punctuation">: </span>DENY</span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>text/plain;charset=UTF-8</span><br><span class="line"><span class="attribute">Content-Length</span><span class="punctuation">: </span>12</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Tue, 18 Jun 2019 01:50:48 GMT</span><br><span class="line"></span><br><span class="line">order id : 1</span><br><span class="line"></span><br><span class="line">Response code: 200; Time: 57ms; Content length: 12 bytes</span><br></pre></td></tr></table></figure>

<p>日志：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">2019-06-18 09:50:48.955  INFO 5288 --- [nio-8080-exec-3] .f.e.a.a.Oauth2FilterSecurityInterceptor : Oauth2FilterSecurityInterceptor doFilter</span><br><span class="line">2019-06-18 09:50:48.955 DEBUG 5288 --- [nio-8080-exec-3] .f.e.a.a.Oauth2FilterSecurityInterceptor : Secure object: FilterInvocation: URL: &#x2F;order&#x2F;1; Attributes: [ROLE_USER]</span><br><span class="line">2019-06-18 09:50:48.956 DEBUG 5288 --- [nio-8080-exec-3] .f.e.a.a.Oauth2FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@f5aeefea: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress&#x3D;127.0.0.1, tokenType&#x3D;bearertokenValue&#x3D;&lt;TOKEN&gt;; Granted Authorities: ROLE_USER</span><br><span class="line">2019-06-18 09:50:48.956  INFO 5288 --- [nio-8080-exec-3] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:开始判断请求 &#x2F;order&#x2F;1 需要的权限</span><br><span class="line">2019-06-18 09:50:48.956  INFO 5288 --- [nio-8080-exec-3] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:请求 &#x2F;order&#x2F;1 需要的权限 - [ROLE_USER]</span><br><span class="line">2019-06-18 09:50:48.956  INFO 5288 --- [nio-8080-exec-3] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:用户 user 拥有的权限 - [ROLE_USER]</span><br><span class="line">2019-06-18 09:50:48.956 DEBUG 5288 --- [nio-8080-exec-3] .f.e.a.a.Oauth2FilterSecurityInterceptor : Authorization successful</span><br><span class="line">2019-06-18 09:50:48.957 DEBUG 5288 --- [nio-8080-exec-3] .f.e.a.a.Oauth2FilterSecurityInterceptor : RunAsManager did not change Authentication object</span><br></pre></td></tr></table></figure>

<h3 id="用户没有资源所需权限"><a href="#用户没有资源所需权限" class="headerlink" title="用户没有资源所需权限"></a>用户没有资源所需权限</h3><p>请求：</p>
<figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">GET http://localhost:8080/order/1</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">403</span> </span><br><span class="line"><span class="attribute">Cache-Control</span><span class="punctuation">: </span>no-store</span><br><span class="line"><span class="attribute">Pragma</span><span class="punctuation">: </span>no-cache</span><br><span class="line"><span class="attribute">X-Content-Type-Options</span><span class="punctuation">: </span>nosniff</span><br><span class="line"><span class="attribute">X-XSS-Protection</span><span class="punctuation">: </span>1; mode=block</span><br><span class="line"><span class="attribute">X-Frame-Options</span><span class="punctuation">: </span>DENY</span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>application/json;charset=UTF-8</span><br><span class="line"><span class="attribute">Transfer-Encoding</span><span class="punctuation">: </span>chunked</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Tue, 18 Jun 2019 01:44:49 GMT</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  &quot;error&quot;: &quot;access_denied&quot;,</span><br><span class="line">  &quot;error_description&quot;: &quot;权限不足!&quot;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Response code: 403; Time: 35ms; Content length: 53 bytes</span><br></pre></td></tr></table></figure>

<p>日志：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">2019-06-18 09:44:44.684  INFO 10624 --- [nio-8080-exec-2] .f.e.a.a.Oauth2FilterSecurityInterceptor : Oauth2FilterSecurityInterceptor doFilter</span><br><span class="line">2019-06-18 09:44:44.685 DEBUG 10624 --- [nio-8080-exec-2] .f.e.a.a.Oauth2FilterSecurityInterceptor : Public object - authentication not attempted</span><br><span class="line">2019-06-18 09:44:49.448  INFO 10624 --- [nio-8080-exec-6] .f.e.a.a.Oauth2FilterSecurityInterceptor : Oauth2FilterSecurityInterceptor doFilter</span><br><span class="line">2019-06-18 09:44:49.449 DEBUG 10624 --- [nio-8080-exec-6] .f.e.a.a.Oauth2FilterSecurityInterceptor : Secure object: FilterInvocation: URL: &#x2F;order&#x2F;1; Attributes: [ROLE_ADMIN]</span><br><span class="line">2019-06-18 09:44:49.449 DEBUG 10624 --- [nio-8080-exec-6] .f.e.a.a.Oauth2FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@22d262ad: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress&#x3D;127.0.0.1, tokenType&#x3D;bearertokenValue&#x3D;&lt;TOKEN&gt;; Granted Authorities: ROLE_USER</span><br><span class="line">2019-06-18 09:44:49.450  INFO 10624 --- [nio-8080-exec-6] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:开始判断请求 &#x2F;order&#x2F;1 需要的权限</span><br><span class="line">2019-06-18 09:44:49.450  INFO 10624 --- [nio-8080-exec-6] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:请求 &#x2F;order&#x2F;1 需要的权限 - [ROLE_ADMIN]</span><br><span class="line">2019-06-18 09:44:49.450  INFO 10624 --- [nio-8080-exec-6] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:用户 user 拥有的权限 - [ROLE_USER]</span><br><span class="line">2019-06-18 09:44:49.451  INFO 10624 --- [nio-8080-exec-6] c.f.e.a.a.Oauth2AccessDecisionManager    : [决策管理器]:用户 user 没有访问资源 &#x2F;order&#x2F;1 的权限!</span><br></pre></td></tr></table></figure>

<p>返回结果和日志符合期望结果</p>
<h2 id="参考资源"><a href="#参考资源" class="headerlink" title="参考资源"></a>参考资源</h2><p><a target="_blank" rel="noopener" href="http://www.spring4all.com/article/422">http://www.spring4all.com/article/422</a></p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/Spring-Security-Oauth2%E4%BB%A4%E7%89%8C%E5%A2%9E%E5%8A%A0%E9%A2%9D%E5%A4%96%E4%BF%A1%E6%81%AF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/26/Spring-Security-Oauth2%E4%BB%A4%E7%89%8C%E5%A2%9E%E5%8A%A0%E9%A2%9D%E5%A4%96%E4%BF%A1%E6%81%AF/" class="post-title-link" itemprop="url">Spring-Security-Oauth2令牌增加额外信息</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 11:13:38" itemprop="dateCreated datePublished" datetime="2019-06-26T11:13:38+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/oauth2/" itemprop="url" rel="index"><span itemprop="name">oauth2</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>在实现了 Oauth2 后，我想要在令牌增加中额外信息，那么该怎么做？</p>
<p>下面是我的做法，首先实现 <code>org.springframework.security.oauth2.provider.token.TokenEnhancer</code> 接口：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.fengxuechao.examples.auth.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.common.OAuth2AccessToken;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.OAuth2Authentication;</span><br><span class="line"><span class="keyword">import</span> org.springframework.security.oauth2.provider.token.TokenEnhancer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * token 额外信息</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> fengxuechao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 0.1</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2019/5/16</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomTokenEnhancer</span> <span class="keyword">implements</span> <span class="title">TokenEnhancer</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> OAuth2AccessToken <span class="title">enhance</span><span class="params">(OAuth2AccessToken accessToken, OAuth2Authentication authentication)</span> </span>&#123;</span><br><span class="line">        Map&lt;String, Object&gt; additionalInfo = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        additionalInfo.put(<span class="string">&quot;organization&quot;</span>, authentication.getName() + randomAlphabetic(<span class="number">4</span>));</span><br><span class="line">        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);</span><br><span class="line">        <span class="keyword">return</span> accessToken;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在 <code>AuthorizationServerConfigurerAdapter</code> 认证服务代码中配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AuthorizationServerConfigInJwt</span> <span class="keyword">extends</span> <span class="title">AuthorizationServerConfigurerAdapter</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(AuthorizationServerEndpointsConfigurer endpoints)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// token 携带额外信息</span></span><br><span class="line">        TokenEnhancerChain tokenEnhancerChain = <span class="keyword">new</span> TokenEnhancerChain();</span><br><span class="line">        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtTokenEnhancer()));</span><br><span class="line">        endpoints</span><br><span class="line">                .tokenStore(tokenStore())</span><br><span class="line">                .tokenEnhancer(tokenEnhancerChain)</span><br><span class="line">                .userDetailsService(userDetailsService)</span><br><span class="line">                .authenticationManager(authenticationManager)</span><br><span class="line">                .setClientDetailsService(clientDetailsService);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Token 额外信息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> TokenEnhancer <span class="title">tokenEnhancer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> CustomTokenEnhancer();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * jwt token：使用了非对称密钥对来签署令牌:</span></span><br><span class="line"><span class="comment">     * 1.生成 JKS Java KeyStore 文件：keytool -genkeypair -alias jwt_rsa -keyalg RSA -keypass 123456 -keystore jwt_rsa.jks -storepass 123456</span></span><br><span class="line"><span class="comment">     * 2.导出公钥：keytool -list -rfc --keystore jwt_rsa.jks | openssl x509 -inform pem -pubkey</span></span><br><span class="line"><span class="comment">     * 3.将 PUBLIC KEY 保存至 public.txt</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> JwtAccessTokenConverter <span class="title">jwtTokenEnhancer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        JwtAccessTokenConverter converter = <span class="keyword">new</span> JwtAccessTokenConverter();</span><br><span class="line">        converter.setKeyPair(<span class="keyword">new</span> KeyStoreKeyFactory(resource, keyStorePass.toCharArray()).getKeyPair(keyPairAlias));</span><br><span class="line">        <span class="comment">// 使用对称密钥来签署令牌</span></span><br><span class="line">        <span class="comment">// converter.setSigningKey(&quot;fengxuechao.littlefxc&quot;);</span></span><br><span class="line">        <span class="keyword">return</span> converter;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或者 <code>tokenServices.setTokenEnhancer(tokenEnhancer);</code></p>
<p>最后演示一下最终效果：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;access_token&quot;</span>: <span class="string">&quot;4aae3856-bc33-4e4d-86bc-eb475fc45569&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;token_type&quot;</span>: <span class="string">&quot;bearer&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;refresh_token&quot;</span>: <span class="string">&quot;fe2ed35d-5c53-4610-abb7-c1053cba6803&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;expires_in&quot;</span>: <span class="number">119</span>,</span><br><span class="line">  <span class="attr">&quot;scope&quot;</span>: <span class="string">&quot;read&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;organization&quot;</span>: <span class="string">&quot;userAKqz&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>jwt </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;access_token&quot;</span>: <span class="string">&quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsicmVhZCJdLCJvcmdhbml6YXRpb24iOiJ1c2VyZWx2ayIsImV4cCI6MTU2MDQ4NDI0OCwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjliNTU2ZTBiLTZlZmQtNDkwZC05OGMwLWIzYzYwNjM2ZDczMCIsImNsaWVudF9pZCI6ImNsaWVudCJ9.oaqlviXcQPCLAZP8cV7v-WA75AoiodiG6d2WR9yqJhOFCg7LDsnCjk63J59sq434CZHRIOkCgMi2hVJHOc4MTIFce61Kk046G3-yK313CtMy5LWeVXdKbAHH0gcuoDO3OCJ7u7GzngPtA6bVfxjJFNJ6MmFxEnFPjB5dos9Bb8zYduE2ELMH2aTCS-67R_aQ0BCZaYo5NMH1_jqz9d1hI_kpBx3auR_d2Vh1eJiC_f9Z-rTmRvXdwQefhwgXZ1UCWjV0NuoCqFO3KicEhjGOkqXZ5eh0vGR5zKwKJfCys1lNgXjXVVntHYkXt96ymQ9477pCAWCONZsbkM7244500Q&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;token_type&quot;</span>: <span class="string">&quot;bearer&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;refresh_token&quot;</span>: <span class="string">&quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsicmVhZCJdLCJvcmdhbml6YXRpb24iOiJ1c2VyZWx2ayIsImF0aSI6IjliNTU2ZTBiLTZlZmQtNDkwZC05OGMwLWIzYzYwNjM2ZDczMCIsImV4cCI6MTU2MDQ4NzcyOCwiYXV0aG9yaXRpZXMiOlsiUk9MRV9VU0VSIl0sImp0aSI6IjJhNTUxOWJjLWUzYTAtNGJjOC1hNTRkLTlmMDNiMjYwNjZkNCIsImNsaWVudF9pZCI6ImNsaWVudCJ9.BgY6N0kzxVApFD-C7UVMDmczSoMY9tglnKzTkybfneoeAAs8ljftIwA5sPWua28Xhl-MNAQ9HL6Q6ou-EbgFlcHC2uPPbJ5silnPLPdTnvVko9l-8w-3WLPk96YbODdQemqFZHSrR1lPmXHB5sR7QjncxGxvuSYZEtPXxZz39lJbyQLSflXADqlk4ZV3BxS-M7d8FcTJEM1uTgwUBSns2N6AZnTkd2FnGskadaV2qhky5TznJjQqRETVS8xCiZCFYwCq5sAMHOj-_BrwlmCeoPfcy38ofbql-qVWfQJiAeU7yWLlAu_hd-zRIIbv-dqRmSF9T9rCxVPv84ptddO1Hw&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;expires_in&quot;</span>: <span class="number">119</span>,</span><br><span class="line">  <span class="attr">&quot;scope&quot;</span>: <span class="string">&quot;read&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;organization&quot;</span>: <span class="string">&quot;userelvk&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;jti&quot;</span>: <span class="string">&quot;9b556e0b-6efd-490d-98c0-b3c60636d730&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最终返回的 Token 信息中多了一个属性 <code>organization</code>，结果符合期望结果。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/26/Springboot%E4%BD%BF%E7%94%A8-JsonView%E8%BF%87%E6%BB%A4%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/26/Springboot%E4%BD%BF%E7%94%A8-JsonView%E8%BF%87%E6%BB%A4%E5%AF%B9%E8%B1%A1%E5%B1%9E%E6%80%A7/" class="post-title-link" itemprop="url">Springboot使用@JsonView过滤对象属性</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-26 08:47:15" itemprop="dateCreated datePublished" datetime="2019-06-26T08:47:15+08:00">2019-06-26</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/springboot/" itemprop="url" rel="index"><span itemprop="name">springboot</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>@JsonView是Jackson的一个注解，可以用来过滤序列化对象的字段属性，是你可以选择序列化对象哪些属性，哪些过滤掉。</p>
<h2 id="使用步骤"><a href="#使用步骤" class="headerlink" title="使用步骤"></a>使用步骤</h2><ol>
<li><p>使用接口来声明多个视图</p>
</li>
<li><p>在值对象的get方法上指定视图</p>
</li>
<li><p>在Controller方法上指定视图</p>
</li>
</ol>
<h2 id="步骤-1：使用接口来声明多个视图"><a href="#步骤-1：使用接口来声明多个视图" class="headerlink" title="步骤 1：使用接口来声明多个视图"></a>步骤 1：使用接口来声明多个视图</h2><p>使用同一个对象，面对不同的场景，去声明多个视图。</p>
<p>例如：</p>
<p>有一个 User 对象，里面有id、username、password、birthday等属性</p>
<ul>
<li><p>场景1：获得对象的用户名、密码</p>
</li>
<li><p>场景2：获得对象的全部属性</p>
</li>
</ul>
<p>为了测试，创建一个User实体对象，加入两个接口 UserSimpleView，UserDetailView</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserSimpleView</span> </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDetailView</span> <span class="keyword">extends</span> <span class="title">UserSimpleView</span> </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotBlank(message = &quot;密码不能为空&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Past(message = &quot;生日必须是过去的时间&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Date birthday;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getUsername</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUsername</span><span class="params">(String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.username = username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPassword</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPassword</span><span class="params">(String password)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Date <span class="title">getBirthday</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> birthday;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBirthday</span><span class="params">(Date birthday)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.birthday = birthday;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="步骤-2：在值对象的get方法上指定视图"><a href="#步骤-2：在值对象的get方法上指定视图" class="headerlink" title="步骤 2：在值对象的get方法上指定视图"></a>步骤 2：在值对象的get方法上指定视图</h2><p>在实体类 User 里的 get 方法上面加上 @JsonView 注解，并将它绑定到一个指定接口</p>
<p>分两类</p>
<ul>
<li><p>@JsonView(UserSimpleView.class)：绑定 id、username、birthday属性</p>
</li>
<li><p>@JsonView(UserDetailView.class)：绑定 password 属性，继承 UserSimpleView 接口（相当于绑了 UserSimpleView 绑定的属性）</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserSimpleView</span> </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserDetailView</span> <span class="keyword">extends</span> <span class="title">UserSimpleView</span> </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotBlank(message = &quot;密码不能为空&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Past(message = &quot;生日必须是过去的时间&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Date birthday;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getUsername</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUsername</span><span class="params">(String username)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.username = username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPassword</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPassword</span><span class="params">(String password)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.password = password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@JsonView(UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Date <span class="title">getBirthday</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> birthday;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setBirthday</span><span class="params">(Date birthday)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.birthday = birthday;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="步骤-3：在Controller方法上指定视图"><a href="#步骤-3：在Controller方法上指定视图" class="headerlink" title="步骤 3：在Controller方法上指定视图"></a>步骤 3：在Controller方法上指定视图</h2><p>在controller中俩个方法分别加上@JsonView注解，在分配上不同场景的接口</p>
<ul>
<li><p>user1：输出视图1</p>
</li>
<li><p>user2：输出视图2</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;user&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span></span><br><span class="line">    <span class="meta">@JsonView(User.UserSimpleView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">query</span><span class="params">(UserQueryCondition condition)</span> </span>&#123;</span><br><span class="line">        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));</span><br><span class="line"></span><br><span class="line">        List&lt;User&gt; users = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        users.add(<span class="keyword">new</span> User());</span><br><span class="line">        users.add(<span class="keyword">new</span> User());</span><br><span class="line">        users.add(<span class="keyword">new</span> User());</span><br><span class="line">        <span class="keyword">return</span> users;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * &#123;id:\d+&#125;:正则表示只接受数字</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping(&quot;&#123;id:\\d+&#125;&quot;)</span></span><br><span class="line">    <span class="meta">@JsonView(User.UserDetailView.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getInfo</span><span class="params">(<span class="meta">@PathVariable</span> String id)</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User();</span><br><span class="line">        user.setId(id);</span><br><span class="line">        user.setUsername(<span class="string">&quot;tom&quot;</span>);</span><br><span class="line">        user.setPassword(<span class="string">&quot;tom&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> user;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">GET http://localhost:8080/user</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">200</span> </span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>application/json;charset=UTF-8</span><br><span class="line"><span class="attribute">Transfer-Encoding</span><span class="punctuation">: </span>chunked</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Wed, 26 Jun 2019 00:41:03 GMT</span><br><span class="line"></span><br><span class="line">[</span><br><span class="line">  &#123;</span><br><span class="line">    &quot;id&quot;: null,</span><br><span class="line">    &quot;username&quot;: null,</span><br><span class="line">    &quot;birthday&quot;: null</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    &quot;id&quot;: null,</span><br><span class="line">    &quot;username&quot;: null,</span><br><span class="line">    &quot;birthday&quot;: null</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line">    &quot;id&quot;: null,</span><br><span class="line">    &quot;username&quot;: null,</span><br><span class="line">    &quot;birthday&quot;: null</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>返回结果中没有密码属性</p>
<figure class="highlight"><figcaption><span>request</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">GET http://localhost:8080/user/1</span><br><span class="line"></span><br><span class="line"><span class="meta">HTTP/1.1</span> <span class="number">200</span> </span><br><span class="line"><span class="attribute">Content-Type</span><span class="punctuation">: </span>application/json;charset=UTF-8</span><br><span class="line"><span class="attribute">Transfer-Encoding</span><span class="punctuation">: </span>chunked</span><br><span class="line"><span class="attribute">Date</span><span class="punctuation">: </span>Wed, 26 Jun 2019 00:41:56 GMT</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line">  &quot;id&quot;: &quot;1&quot;,</span><br><span class="line">  &quot;username&quot;: &quot;tom&quot;,</span><br><span class="line">  &quot;password&quot;: &quot;tom&quot;,</span><br><span class="line">  &quot;birthday&quot;: null</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>返回结果中包含了密码字段。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>说明 @OneView 只会序列化 username、password 属性，TwoView 会序列化username、password、realName、sex属性。</p>
<p>因此想设置不同接口的不同场景,可以用 @JsonView 达到某些目的。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/20/MySQL%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/20/MySQL%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/" class="post-title-link" itemprop="url">MySQL数据类型</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-20 16:23:37" itemprop="dateCreated datePublished" datetime="2019-06-20T16:23:37+08:00">2019-06-20</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:48" itemprop="dateModified" datetime="2021-03-25T21:15:48+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/RDBMS/" itemprop="url" rel="index"><span itemprop="name">RDBMS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="MySQL数据类型"><a href="#MySQL数据类型" class="headerlink" title="MySQL数据类型"></a>MySQL数据类型</h1><ul>
<li>数字类型<ul>
<li>整数: tinyint、smallint、mediumint、int、bigint</li>
<li>浮点数: float、double、real、decimal</li>
</ul>
</li>
<li>日期和时间: date、time、datetime、timestamp、year</li>
<li>字符串类型<ul>
<li>字符串: char、varchar</li>
<li>文本: tinytext、text、mediumtext、longtext</li>
</ul>
</li>
<li>二进制(可用来存储图片、音乐等): tinyblob、blob、mediumblob、longblob</li>
</ul>
<h2 id="数字类型"><a href="#数字类型" class="headerlink" title="数字类型"></a>数字类型</h2><h3 id="整型"><a href="#整型" class="headerlink" title="整型"></a>整型</h3><table>
<thead>
<tr>
<th>type</th>
<th>Storage(Bytes)</th>
<th>Signed Range</th>
<th>Unsigned Range</th>
</tr>
</thead>
<tbody><tr>
<td>TINYINT</td>
<td>1</td>
<td>-128-127</td>
<td>0-255</td>
</tr>
<tr>
<td>SMALLINT</td>
<td>2</td>
<td>-32768-32767</td>
<td>0-65535</td>
</tr>
<tr>
<td>MEDIUMINT</td>
<td>3</td>
<td>-8388608-8388607</td>
<td>0-16777215</td>
</tr>
<tr>
<td>INT</td>
<td>4</td>
<td>-2147483648-2147483647</td>
<td>0-4294967295</td>
</tr>
<tr>
<td>BIGINT</td>
<td>8</td>
<td>-9223372036854775808-9223372036854775807</td>
<td>0-18446744073709551615</td>
</tr>
</tbody></table>
<h3 id="浮点型"><a href="#浮点型" class="headerlink" title="浮点型"></a>浮点型</h3><table>
<thead>
<tr>
<th>属性</th>
<th>存储空间</th>
<th>精度</th>
<th>精确性</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>FLOAT(M, D)</td>
<td>4 bytes</td>
<td>单精度</td>
<td>非精确</td>
<td>单精度浮点型，m总个数，d小数位</td>
</tr>
<tr>
<td>DOUBLE(M, D)</td>
<td>8 bytes</td>
<td>双精度</td>
<td>比Float精度高</td>
<td>双精度浮点型，m总个数，d小数位</td>
</tr>
</tbody></table>
<ul>
<li>FLOAT容易造成精度丢失</li>
</ul>
<h3 id="定点数DECIMAL"><a href="#定点数DECIMAL" class="headerlink" title="定点数DECIMAL"></a>定点数DECIMAL</h3><ul>
<li>高精度的数据类型，常用来存储交易相关的数据</li>
<li>DECIMAL(M,N).M代表总精度，N代表小数点右侧的位数（标度）</li>
<li>1 &lt; M &lt; 254, 0 &lt; N &lt; 60;</li>
<li>存储空间变长</li>
</ul>
<h2 id="时间类型"><a href="#时间类型" class="headerlink" title="时间类型"></a>时间类型</h2><table>
<thead>
<tr>
<th>类型</th>
<th>字节</th>
<th>例</th>
<th>精确性</th>
</tr>
</thead>
<tbody><tr>
<td>DATE</td>
<td>三字节</td>
<td>2015-05-01</td>
<td>精确到年月日</td>
</tr>
<tr>
<td>TIME</td>
<td>三字节</td>
<td>11:12:00</td>
<td>精确到时分秒</td>
</tr>
<tr>
<td>DATETIME</td>
<td>八字节</td>
<td>2015-05-01 11::12:00</td>
<td>精确到年月日时分秒</td>
</tr>
<tr>
<td>TIMESTAMP</td>
<td></td>
<td>2015-05-01 11::12:00</td>
<td>精确到年月日时分秒</td>
</tr>
</tbody></table>
<ul>
<li>MySQL在<code>5.6.4</code>版本之后，<code>TIMESTAMP</code>和<code>DATETIME</code>支持到微秒。</li>
<li><code>TIMESTAMP</code>会根据系统时区进行转换，<code>DATETIME</code>则不会</li>
<li>存储范围的区别  <ul>
<li><code>TIMESTAMP</code>存储范围：1970-01-01 00::00:01 to 2038-01-19 03:14:07</li>
<li><code>DATETIME</code>的存储范围：1000-01-01 00:00:00 to 9999-12-31 23:59:59</li>
</ul>
</li>
<li>一般使用<code>TIMESTAMP</code>国际化</li>
<li>如存时间戳使用数字类型<code>BIGINT</code></li>
</ul>
<h2 id="字符串类型"><a href="#字符串类型" class="headerlink" title="字符串类型"></a>字符串类型</h2><table>
<thead>
<tr>
<th>类型</th>
<th>单位</th>
<th>最大</th>
<th>特性</th>
</tr>
</thead>
<tbody><tr>
<td>CHAR</td>
<td>字符</td>
<td>最大为255字符</td>
<td>存储定长，容易造成空间的浪费</td>
</tr>
<tr>
<td>VARCHAR</td>
<td>字符</td>
<td>可以超过255个字符</td>
<td>存储变长，节省存储空间</td>
</tr>
<tr>
<td>TEXT</td>
<td>字节</td>
<td>总大小为65535字节，约为64KB</td>
<td>-</td>
</tr>
</tbody></table>
<ul>
<li>TEXT在MySQL内部大多存储格式为溢出页，效率不如CHAR</li>
<li>Mysql默认为utf-8，那么在英文模式下1个字符=1个字节，在中文模式下1个字符=3个字节。</li>
</ul>
<h2 id="其它"><a href="#其它" class="headerlink" title="其它"></a>其它</h2><p><code>SERIAL</code> 是 <code>BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE</code> 的别名。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/20/SQL%E5%8F%8D%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/20/SQL%E5%8F%8D%E6%A8%A1%E5%BC%8F/" class="post-title-link" itemprop="url"><SQL反模式></a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-20 14:47:47" itemprop="dateCreated datePublished" datetime="2019-06-20T14:47:47+08:00">2019-06-20</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/SQL/" itemprop="url" rel="index"><span itemprop="name">SQL</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="《SQL反模式》-阅读笔记"><a href="#《SQL反模式》-阅读笔记" class="headerlink" title="《SQL反模式》 阅读笔记"></a>《SQL反模式》 阅读笔记</h2><h3 id="反模式分类"><a href="#反模式分类" class="headerlink" title="反模式分类"></a>反模式分类</h3><ul>
<li>逻辑数据库设计反模式</li>
<li>物理书库设计反模式</li>
<li>查询反模式</li>
<li>应用程序开发反模式</li>
</ul>
<h3 id="反模式分解"><a href="#反模式分解" class="headerlink" title="反模式分解"></a>反模式分解</h3><ul>
<li>目的</li>
<li>反模式</li>
<li>如何识别反模式</li>
<li>合理使用反模式</li>
<li>解决方案</li>
</ul>
<h3 id="ER-图示例"><a href="#ER-图示例" class="headerlink" title="ER 图示例"></a>ER 图示例</h3><p><img src="" alt="ER 图示例"></p>
<h3 id="范例数据库"><a href="#范例数据库" class="headerlink" title="范例数据库"></a>范例数据库</h3><p><code>SERIAL</code> 是 MySQL 中 <code>BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE</code> 的别名</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Accounts (</span><br><span class="line">    account_id         SERIAL <span class="keyword">PRIMARY</span> KEY,</span><br><span class="line">    account_name       <span class="type">VARCHAR</span>(<span class="number">20</span>),</span><br><span class="line">    first_name         <span class="type">VARCHAR</span>(<span class="number">20</span>),</span><br><span class="line">    last_name          <span class="type">VARCHAR</span>(<span class="number">20</span>),</span><br><span class="line">    email              <span class="type">VARCHAR</span>(<span class="number">100</span>),</span><br><span class="line">    password_hash      <span class="type">CHAR</span>(<span class="number">64</span>),</span><br><span class="line">    portrait_image     <span class="type">BLOB</span>,</span><br><span class="line">    hourly_rate        <span class="type">NUMERIC</span>(<span class="number">9</span>,<span class="number">2</span>)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> BugStatus (</span><br><span class="line">    `status` <span class="type">VARCHAR</span>(<span class="number">20</span>) <span class="keyword">PRIMARY</span> KEY</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Bugs (</span><br><span class="line">    bug_id             SERIAL <span class="keyword">PRIMARY</span> KEY,</span><br><span class="line">    date_reported      <span class="type">DATE</span> <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    summary            <span class="type">VARCHAR</span>(<span class="number">80</span>),</span><br><span class="line">    description        <span class="type">VARCHAR</span>(<span class="number">1000</span>),</span><br><span class="line">    resolition         <span class="type">VARCHAR</span>(<span class="number">1000</span>),</span><br><span class="line">    reported_by        <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    assigned_to        <span class="type">BIGINT</span> UNSIGNED,</span><br><span class="line">    verified_by        <span class="type">BIGINT</span> UNSIGNED,</span><br><span class="line">    `status`           <span class="type">VARCHAR</span>(<span class="number">20</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">&#x27;NEW&#x27;</span>,</span><br><span class="line">    priority           <span class="type">VARCHAR</span>(<span class="number">20</span>),</span><br><span class="line">    hours              <span class="type">NUMERIC</span>(<span class="number">9</span>,<span class="number">2</span>),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (reported_by) <span class="keyword">REFERENCES</span> Accounts(account_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (assigned_to) <span class="keyword">REFERENCES</span> Accounts(account_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (verified_by) <span class="keyword">REFERENCES</span> Accounts(account_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (`status`) <span class="keyword">REFERENCES</span> BugStatus(`status`)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Comments (</span><br><span class="line">    comment_id         SERIAL <span class="keyword">PRIMARY</span> KEY,</span><br><span class="line">    bug_id             <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    author             <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    comment_date       DATETIME <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    comment            TEXT <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (bug_id) <span class="keyword">REFERENCES</span> Bugs(bug_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (author) <span class="keyword">REFERENCES</span> Accounts(account_id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Screenhots (</span><br><span class="line">    bug_id             <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    image_id           <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    screenshot_image   <span class="type">BLOB</span>,</span><br><span class="line">    caption            <span class="type">VARCHAR</span>(<span class="number">100</span>),</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY        (bug_id,image_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (bug_id) <span class="keyword">REFERENCES</span> Bugs(bug_id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Tags (</span><br><span class="line">    bug_id             <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    tag                <span class="type">VARCHAR</span>(<span class="number">20</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY        (bug_id,tag),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (bug_id) <span class="keyword">REFERENCES</span> Bugs(bug_id)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> Products (</span><br><span class="line">    product_id         SERIAL <span class="keyword">PRIMARY</span> KEY,</span><br><span class="line">    product_name       <span class="type">VARCHAR</span>(<span class="number">50</span>) <span class="keyword">NOT</span> <span class="keyword">NULL</span></span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> IF <span class="keyword">NOT</span> <span class="keyword">EXISTS</span> BugsProducts (</span><br><span class="line">    bug_id             <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    product_id         <span class="type">BIGINT</span> UNSIGNED <span class="keyword">NOT</span> <span class="keyword">NULL</span>,</span><br><span class="line">    <span class="keyword">PRIMARY</span> KEY        (bug_id,product_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (bug_id) <span class="keyword">REFERENCES</span> Bugs(bug_id),</span><br><span class="line">    <span class="keyword">FOREIGN</span> KEY (product_id) <span class="keyword">REFERENCES</span> Products(product_id)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/06/11/linux%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/06/11/linux%E5%B8%B8%E7%94%A8%E5%91%BD%E4%BB%A4/" class="post-title-link" itemprop="url">linux常用命令</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-06-11 23:03:37" itemprop="dateCreated datePublished" datetime="2019-06-11T23:03:37+08:00">2019-06-11</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:49" itemprop="dateModified" datetime="2021-03-25T21:15:49+08:00">2021-03-25</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="文件系统常用命令"><a href="#文件系统常用命令" class="headerlink" title="文件系统常用命令"></a>文件系统常用命令</h2><p><code>ls /</code> : 查看根目录下的子节点（文件夹和文件）信息</p>
<p><code>ls -al</code> : -a 显示隐藏文件 -l 以更详细的列表形式显示</p>
<p><code>mkdir aaa</code> : 创建相对路径文件夹的写法</p>
<p><code>mkdir -p aaa/bbb/ccc</code></p>
<p><code>rmdir</code> : 可以删除空目录</p>
<p><code>rm -r aaa</code> : 可以把 aaa 整个文件夹及其中的所有子节点全都删除</p>
<p><code>rm -fr aaa</code> : 强制删除 aaa</p>
<p><code>touch somefile.txt</code> : 创建一个空文件</p>
<p><code>&gt;</code> : 重定向 <code>echo &quot;利用 &gt; 重定向的功能，将一定指令的输出结果写入到一个文件中，会覆盖原文件内容&quot; &gt; somefile.txt</code></p>
<p><code>&gt;&gt;</code> : 追加 <code>echo &quot;利用 &gt;&gt; 可以把字符串追加到一个文件中，不会覆盖原文件内容&quot; &gt;&gt; somefile.txt</code></p>
<h2 id="vi-编辑器的一些快捷键"><a href="#vi-编辑器的一些快捷键" class="headerlink" title="vi 编辑器的一些快捷键"></a>vi 编辑器的一些快捷键</h2><h3 id="一般模式"><a href="#一般模式" class="headerlink" title="一般模式"></a>一般模式</h3><p><code>a</code> : 在光标后一位开始插入</p>
<p><code>A</code> : 在该行的最后插入</p>
<p><code>I</code> : 在该行的最前面插入</p>
<p><code>gg</code> : 直接跳到文件的首行</p>
<p><code>G</code> : </p>
<h3 id="编辑模式"><a href="#编辑模式" class="headerlink" title="编辑模式"></a>编辑模式</h3>
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/05/23/Consul%E4%BD%BF%E7%94%A8%E8%AE%B0%E5%BD%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/05/23/Consul%E4%BD%BF%E7%94%A8%E8%AE%B0%E5%BD%95/" class="post-title-link" itemprop="url">Consul使用记录</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-05-23 09:53:08" itemprop="dateCreated datePublished" datetime="2019-05-23T09:53:08+08:00">2019-05-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:48" itemprop="dateModified" datetime="2021-03-25T21:15:48+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83/" itemprop="url" rel="index"><span itemprop="name">注册中心</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="1-consul-集群模式"><a href="#1-consul-集群模式" class="headerlink" title="1. consul 集群模式"></a>1. consul 集群模式</h2><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul agent -server -data-dir=./data/ -node=s1 -<span class="built_in">bind</span>=192.168.217.86 -ui -rejoin -client=0.0.0.0 -bootstrap-expect=1 -ui</span><br></pre></td></tr></table></figure>

<p>参数介绍：</p>
<ul>
<li>-server 表示是以服务端身份启动，去掉这个参数表示 <code>client</code> 模式</li>
<li>-bind 表示绑定到哪个ip（有些服务器会绑定多块网卡，可以通过bind参数强制指定绑定的ip），一般是本机IP</li>
<li>-client 指定客户端访问的ip(consul有丰富的api接口，这里的客户端指浏览器或调用方)，0.0.0.0表示不限客户端ip</li>
<li>-bootstrap-expect=3 表示server集群最低节点数为3，低于这个值将工作不正常(注：类似zookeeper一样，通常集群数为奇数，方便选举，consul采用的是raft算法)</li>
<li>-data-dir 表示指定数据的存放(持久化)目录（该目录必须存在）</li>
<li>-node 表示节点在web ui中显示的名称</li>
</ul>
<p>启动成功后，终端窗口不要关闭，可以在浏览器里，访问下，类似 <a target="_blank" rel="noopener" href="http://192.168.212.73:8500/%EF%BC%8C">http://192.168.212.73:8500/，</a> 正常的话，可以正常打开web界面。</p>
<p>为了防止终端关闭后，consul退出，可以在刚才命令上，加点东西，类似：<code>nohup xxx  &gt; /dev/null 2&gt;&amp;1 &amp; </code></p>
<h3 id="1-1-命令行建立-consul-集群"><a href="#1-1-命令行建立-consul-集群" class="headerlink" title="1.1. 命令行建立 consul 集群"></a>1.1. 命令行建立 consul 集群</h3><p>服务端1：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul agent -server -bootstrap-expect=2 -data-dir=./data/ -<span class="built_in">bind</span>=192.168.217.134 -client=0.0.0.0 -node=s1 -ui</span><br></pre></td></tr></table></figure>

<p>服务端2：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul agent -server -bootstrap-expect=2 -data-dir=./data/ -<span class="built_in">bind</span>=192.168.217.72 -client=0.0.0.0 -join 192.168.217.134 -node=s2 -ui</span><br></pre></td></tr></table></figure>

<p>服务端3：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul agent -server -bootstrap-expect=2 -data-dir=./data/ -<span class="built_in">bind</span>=192.168.217.86 -client=0.0.0.0 -join 192.168.217.134 -node=s3 -ui</span><br></pre></td></tr></table></figure>

<p>客户端1：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul agent -data-dir=./data/ -<span class="built_in">bind</span>=192.168.217.87 -client=0.0.0.0 -join 192.168.217.134 -node=c1 -ui</span><br></pre></td></tr></table></figure>

<h3 id="1-2-配置文件方式建立-consul-集群"><a href="#1-2-配置文件方式建立-consul-集群" class="headerlink" title="1.2. 配置文件方式建立 consul 集群"></a>1.2. 配置文件方式建立 consul 集群</h3><p><img src="https://img-blog.csdnimg.cn/20190522164211256.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>例：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="comment">/* 表示server集群最低节点数 */</span></span><br><span class="line">  <span class="attr">&quot;bootstrap_expect&quot;</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="comment">/* 表示该节点绑定的地址, 默认0.0.0.0 */</span></span><br><span class="line">  <span class="attr">&quot;bind_addr&quot;</span>: <span class="string">&quot;192.168.217.86&quot;</span>,</span><br><span class="line">  <span class="comment">/* 访问该节点的地址, 默认127.0.0.1*/</span></span><br><span class="line">  <span class="attr">&quot;client_addr&quot;</span>: <span class="string">&quot;0.0.0.0&quot;</span>,</span><br><span class="line">  <span class="comment">/* 访问该节点的数据中心*/</span></span><br><span class="line">  <span class="attr">&quot;datacenter&quot;</span>: <span class="string">&quot;data-center-1&quot;</span>,</span><br><span class="line">  <span class="comment">/* 必须, 数据保存的地址*/</span></span><br><span class="line">  <span class="attr">&quot;data_dir&quot;</span>: <span class="string">&quot;/home/awifi/consul-server/data&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;addresses&quot;</span>: &#123;</span><br><span class="line">    <span class="comment">/* 表示该节点绑定的dns地址, 以空格分隔的要绑定的地址列表*/</span></span><br><span class="line">    <span class="attr">&quot;dns&quot;</span>: <span class="string">&quot;192.168.217.86&quot;</span>,</span><br><span class="line">    <span class="comment">/* 表示该节点绑定的http地址, 以空格分隔的要绑定的地址列表*/</span></span><br><span class="line">    <span class="attr">&quot;http&quot;</span>: <span class="string">&quot;192.168.217.86 127.0.0.1&quot;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">/* 节点名，必须*/</span></span><br><span class="line">  <span class="attr">&quot;node_name&quot;</span>: <span class="string">&quot;server:192.168.212.73:8500&quot;</span>,</span><br><span class="line">  <span class="attr">&quot;rejoin_after_leave&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="comment">/* 表示该节点类型是server*/</span></span><br><span class="line">  <span class="attr">&quot;server&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="comment">/* 允许在第一次尝试失败时重试连接 */</span></span><br><span class="line"><span class="attr">&quot;retry_join&quot;</span>: [</span><br><span class="line">        <span class="string">&quot;192.168.217.72&quot;</span>,</span><br><span class="line">        <span class="string">&quot;192.168.217.134&quot;</span></span><br><span class="line">    ],</span><br><span class="line">  <span class="comment">/* 表示开启web界面*/</span></span><br><span class="line">  <span class="attr">&quot;ui&quot;</span>: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在另一台机器上执行<br>./consul join 192.168.217.86<br>或者可以加入配置</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;start_join&quot;</span>:[],</span><br><span class="line">  <span class="attr">&quot;retry_join&quot;</span>:[]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>start_join</code>：等同于 命令行参数<code> -join</code> : 表示启动时加入的集群地址<br><code>retry_join</code>：等同于 命令行参数<code> -retry-join</code> : 允许在第一次尝试失败时重试连接，该列表可以包含IPv4，IPv6或DNS地址。</p>
<h4 id="1-2-1-为什么-http-地址要绑定-127-0-0-1-？"><a href="#1-2-1-为什么-http-地址要绑定-127-0-0-1-？" class="headerlink" title="1.2.1.  为什么 http 地址要绑定 127.0.0.1 ？"></a>1.2.1.  为什么 http 地址要绑定 127.0.0.1 ？</h4><p>如果不绑定127.0.0.1，在该服务器上就会无法使用除 ./consul agent 以外的命令，</p>
<p>例如:<br>组建集群模式的核心命令：<code>consul join 192.168.217.86</code><br>优雅的注销节点的命令：  <code>consul leave</code><br><img src="https://img-blog.csdnimg.cn/20190522164607754.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xpdHRsZV9meGM=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h2 id="2-查看集群状态"><a href="#2-查看集群状态" class="headerlink" title="2. 查看集群状态"></a>2. 查看集群状态</h2><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul operator raft list-peers</span><br></pre></td></tr></table></figure>

<p> 运行结果：</p>
<p><img src="https://img-blog.csdnimg.cn/20190522162138210.png" alt="查看集群状态"></p>
<p>运行结果红色方框部分可以看出集群模式中谁是 <code>leader</code></p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2019/05/23/Java%E9%9B%86%E5%90%88%E5%AD%A6%E4%B9%A0%E4%B9%8BLinkedList/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2019/05/23/Java%E9%9B%86%E5%90%88%E5%AD%A6%E4%B9%A0%E4%B9%8BLinkedList/" class="post-title-link" itemprop="url">Java集合学习之LinkedList</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2019-05-23 09:51:14" itemprop="dateCreated datePublished" datetime="2019-05-23T09:51:14+08:00">2019-05-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-03-25 21:15:48" itemprop="dateModified" datetime="2021-03-25T21:15:48+08:00">2021-03-25</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>双链表实现了List和Deque接口。 实现所有可选列表操作，并允许所有元素（包括null ）。</p>
<p>所有的操作都能像双向列表一样预期。 索引到列表中的操作将从开始或结束遍历列表，以更接近指定的索引为准。</p>
<p><strong>请注意，此实现不同步。</strong> 如果多个线程同时访问链接列表，并且至少有一个线程在结构上修改列表，则必须在外部进行同步。 （结构修改是添加或删除一个或多个元素的任何操作;仅设置元素的值不是结构修改。）<br>这通常通过在自然封装列表的对象上进行同步来实现。 如果没有这样的对象存在，列表应该使用 Collections.synchronizedList 方法“包装”。 这最好在创建时完成，以防止意外的不同步访问列表：</p>
<pre><code>List list = Collections.synchronizedList(new LinkedList(...)); 
</code></pre>
<p>这个类的 iterator 和 listIterator 方法返回的迭代器是故障快速的 ：如果列表在迭代器创建之后的任何时间被结构化地修改，除了通过迭代器自己的remove或add方法之外，<br>迭代器将会抛出一个ConcurrentModificationException 。 因此，面对并发修改，迭代器将快速而干净地失败，而不是在未来未确定的时间冒着任意的非确定性行为。</p>
<p>请注意，迭代器的故障快速行为无法保证，因为一般来说，在不同步并发修改的情况下，无法做出任何硬性保证。<br>失败快速迭代器尽力投入ConcurrentModificationException 。 因此，编写依赖于此异常的程序的正确性将是错误的：迭代器的故障快速行为应仅用于检测错误。</p>
<p>（以上来自 Java8 api）</p>
<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><p>首先看一下 LinkedList 的继承关系：</p>
<p><img src="../images/LinkedListUML.png" alt="LinkedListUML.png"></p>
<h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt;</span></span><br><span class="line"><span class="class">    <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt;</span></span><br><span class="line"><span class="class">    <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>LinkedList 是一个继承于 AbstractSequentialList 的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。<br>最大限度地减少了实现受“连续访问”数据存储（如链接列表）支持的此接口所需的工作,从而以减少实现 List 接口的复杂度。</li>
<li>LinkedList 实现 List 接口，能对它进行序列（有序集合）操作。</li>
<li>LinkedList 实现 Deque 接口，即能将LinkedList当作双端队列使用。</li>
<li>LinkedList 实现了 Cloneable 接口，即覆盖了函数 clone()，能克隆。</li>
<li>LinkedList 实现 java.io.Serializable 接口，这意味着 LinkedList 支持序列化，能通过序列化去传输。</li>
<li>LinkedList 是非同步的。</li>
</ol>
<h3 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">transient</span> <span class="keyword">int</span> size = <span class="number">0</span>;<span class="comment">// list中的元素个数</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 链表头节点</span></span><br><span class="line"><span class="comment">     * 不变式: (first == null &amp;&amp; last == null) || (first.prev == null &amp;&amp; first.item != null)</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">transient</span> Node&lt;E&gt; first;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 链表尾节点</span></span><br><span class="line"><span class="comment">     * 不变式: (first == null &amp;&amp; last == null) || (last.next == null &amp;&amp; last.item != null)</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">transient</span> Node&lt;E&gt; last;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">        E item;<span class="comment">// 实际存放的元素</span></span><br><span class="line">        Node&lt;E&gt; next;<span class="comment">// 后一个节点</span></span><br><span class="line">        Node&lt;E&gt; prev;<span class="comment">// 前一个节点</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 构造函数元素顺序分别为前，自己，后。就像排队一样</span></span><br><span class="line">        Node(Node&lt;E&gt; prev, E element, Node&lt;E&gt; next) &#123;</span><br><span class="line">            <span class="keyword">this</span>.item = element;</span><br><span class="line">            <span class="keyword">this</span>.next = next;</span><br><span class="line">            <span class="keyword">this</span>.prev = prev;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;        </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="构造方法"><a href="#构造方法" class="headerlink" title="构造方法"></a>构造方法</h3><p>由于采用的是链表结构，所以不像 ArrayList 一样，有指定容量的构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line">     </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">      * 构造一个空列表.</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="title">LinkedList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">     &#125;</span><br><span class="line">    </span><br><span class="line">     <span class="comment">/**</span></span><br><span class="line"><span class="comment">      * 构造一个包含指定 collection 中的元素的列表，这些元素按其 collection 的迭代器返回的顺序排列</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="title">LinkedList</span><span class="params">(Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">         <span class="keyword">this</span>();<span class="comment">// 什么都不做</span></span><br><span class="line">         addAll(c);<span class="comment">// 将 c 集合里的元素添加进链表</span></span><br><span class="line">     &#125;</span><br><span class="line">     </span><br><span class="line">     <span class="comment">/**</span></span><br><span class="line"><span class="comment">       * 按照指定集合的迭代器返回的顺序将指定集合中的所有元素追加到此列表的末尾。</span></span><br><span class="line"><span class="comment">       */</span></span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addAll</span><span class="params">(Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> addAll(size, c);</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">checkPositionIndex</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">          <span class="keyword">if</span> (!isPositionIndex(index))</span><br><span class="line">              <span class="keyword">throw</span> <span class="keyword">new</span> IndexOutOfBoundsException(outOfBoundsMsg(index));</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * 判断参数是迭代器或添加操作的有效位置的索引。</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">       <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isPositionIndex</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">           <span class="keyword">return</span> index &gt;= <span class="number">0</span> &amp;&amp; index &lt;= size;</span><br><span class="line">       &#125;</span><br><span class="line">  </span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">       * 从指定位置开始，将指定集合中的所有元素插入此列表。 </span></span><br><span class="line"><span class="comment">       * 将当前位置的元素（如果有）和任何后续元素向右移动（增加其索引）。 </span></span><br><span class="line"><span class="comment">       * 新元素将按照指定集合的迭代器返回的顺序出现在列表中。</span></span><br><span class="line"><span class="comment">       */</span></span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addAll</span><span class="params">(<span class="keyword">int</span> index, Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">          checkPositionIndex(index);<span class="comment">// 检查索引是否正确，即在 0 &lt;= index &lt;= size</span></span><br><span class="line">  </span><br><span class="line">          Object[] a = c.toArray();<span class="comment">// 将 collection 转为数组</span></span><br><span class="line">          <span class="keyword">int</span> numNew = a.length;</span><br><span class="line">          <span class="keyword">if</span> (numNew == <span class="number">0</span>)</span><br><span class="line">              <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">  </span><br><span class="line">          Node&lt;E&gt; pred, succ;<span class="comment">// 声明 pred 为&quot;当前要插入节点的前一个节点&quot;，succ 为&quot;当前要插入节点的后一个节点&quot;</span></span><br><span class="line">          <span class="keyword">if</span> (index == size) &#123;<span class="comment">// 说明要插入元素的位置就在链表的末尾，后置元素为null，前一个元素就是last</span></span><br><span class="line">              succ = <span class="keyword">null</span>;</span><br><span class="line">              pred = last;</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123; <span class="comment">// 说明在链表的中间插入，这时 pred 为原来 index 的 prev，succ 为原来的元素</span></span><br><span class="line">              succ = node(index);<span class="comment">// 利用双向链表的特性，进行更快的遍历</span></span><br><span class="line">              pred = succ.prev;</span><br><span class="line">          &#125;</span><br><span class="line">  </span><br><span class="line">          <span class="keyword">for</span> (Object o : a) &#123;<span class="comment">// 遍历数组，逐个添加</span></span><br><span class="line">              <span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span> E e = (E) o;</span><br><span class="line">              Node&lt;E&gt; newNode = <span class="keyword">new</span> Node&lt;&gt;(pred, e, <span class="keyword">null</span>);</span><br><span class="line">              <span class="keyword">if</span> (pred == <span class="keyword">null</span>)</span><br><span class="line">                  first = newNode;</span><br><span class="line">              <span class="keyword">else</span></span><br><span class="line">                  pred.next = newNode;</span><br><span class="line">              pred = newNode;<span class="comment">// 将新节点作为pred，为下一个元素插入做准备</span></span><br><span class="line"></span><br><span class="line">          &#125;</span><br><span class="line">  </span><br><span class="line">          <span class="keyword">if</span> (succ == <span class="keyword">null</span>) &#123;<span class="comment">// 如果后继元素为空，那么插入完后的最后一个元素，就 pred 就是 last</span></span><br><span class="line">              last = pred;</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;<span class="comment">// 否则就维护最后一个元素和之前的元素之间的关系</span></span><br><span class="line">              pred.next = succ;</span><br><span class="line">              succ.prev = pred;</span><br><span class="line">          &#125;</span><br><span class="line">  </span><br><span class="line">          size += numNew;</span><br><span class="line">          modCount++;<span class="comment">// 链表结构发生改动</span></span><br><span class="line">          <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">       * 返回指定元素索引处的(非空)节点</span></span><br><span class="line"><span class="comment">       * 利用双向链表的特性，进行更快的遍历</span></span><br><span class="line"><span class="comment">       * 双向链表和索引值联系起来：通过一个计数索引值来实现</span></span><br><span class="line"><span class="comment">       *    当我们调用get(int index)时，首先会比较“index”和“双向链表长度的1/2”；</span></span><br><span class="line"><span class="comment">       *    若前者大，则从链表头开始往后查找，直到 index 位置；</span></span><br><span class="line"><span class="comment">       *    否则，从链表末尾开始先前查找，直到 index 位置.</span></span><br><span class="line"><span class="comment">       */</span></span><br><span class="line">      <span class="function">Node&lt;E&gt; <span class="title">node</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">          <span class="comment">// assert isElementIndex(index);</span></span><br><span class="line">      </span><br><span class="line">          <span class="keyword">if</span> (index &lt; (size &gt;&gt; <span class="number">1</span>)) &#123;<span class="comment">// 如果index在链表的前半部分，则从头部节点开始遍历</span></span><br><span class="line">              Node&lt;E&gt; x = first;</span><br><span class="line">              <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; index; i++)</span><br><span class="line">                  x = x.next;</span><br><span class="line">              <span class="keyword">return</span> x;</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;<span class="comment">// 如果index在链表的后半部分，则从尾部节点开始遍历</span></span><br><span class="line">              Node&lt;E&gt; x = last;</span><br><span class="line">              <span class="keyword">for</span> (<span class="keyword">int</span> i = size - <span class="number">1</span>; i &gt; index; i--)</span><br><span class="line">                  x = x.prev;</span><br><span class="line">              <span class="keyword">return</span> x;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="增加-add-E-e"><a href="#增加-add-E-e" class="headerlink" title="增加 add(E e)"></a>增加 add(E e)</h3><p>作为链表，添加新元素就是在链表的末尾插入新元素。</p>
<p>注意，如果末尾元素是 null ，又该如何处理？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将指定的元素追加到此列表的末尾。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">         linkLast(e);</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 链接 e 作为最后一个元素。</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">linkLast</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Node&lt;E&gt; l = last;<span class="comment">// 记录last节点</span></span><br><span class="line">        <span class="keyword">final</span> Node&lt;E&gt; newNode = <span class="keyword">new</span> Node&lt;&gt;(l, e, <span class="keyword">null</span>);<span class="comment">// 初始化新的节点</span></span><br><span class="line"></span><br><span class="line">        last = newNode;</span><br><span class="line">        <span class="keyword">if</span> (l == <span class="keyword">null</span>)<span class="comment">// 末尾元素是 null,是个空列表</span></span><br><span class="line">            first = newNode;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            l.next = newNode;</span><br><span class="line">        size++;</span><br><span class="line">        modCount++;<span class="comment">// 链表结构发生改动</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>LinkedList 还有其他的增加方法：</p>
<ul>
<li>add(int index, E element)：在此列表中指定的位置插入指定的元素。</li>
<li>addAll(Collection&lt;? extends E&gt; c)：添加指定 collection 中的所有元素到此列表的结尾，顺序是指定 collection 的迭代器返回这些元素的顺序。</li>
<li>addAll(int index, Collection&lt;? extends E&gt; c)：将指定 collection 中的所有元素从指定位置开始插入此列表。</li>
<li>AddFirst(E e): 将指定元素插入此列表的开头。</li>
<li>addLast(E e): 将指定元素添加到此列表的结尾。</li>
</ul>
<h3 id="移除"><a href="#移除" class="headerlink" title="移除"></a>移除</h3><p>处理思路：</p>
<ol>
<li>由于插入的元素可能为null，所以要对o进行判断，否则不论是o为null还是遍历的时候元素为null，都会导致报空指针异常</li>
<li>找到元素后，对前后的元素关系重新维护，要考虑到元素是否在头尾的情况</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">remove</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (o == <span class="keyword">null</span>) &#123;<span class="comment">// 是否为 null 的判断</span></span><br><span class="line">            <span class="comment">// 从头节点遍历链表寻找第一个 x(null) 元素</span></span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; x = first; x != <span class="keyword">null</span>; x = x.next) &#123;</span><br><span class="line">                <span class="keyword">if</span> (x.item == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    unlink(x);<span class="comment">// 取消链接 x(null) 元素，重新维护删除元素后的前后关系</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;<span class="comment">// 与上面的逻辑相同</span></span><br><span class="line">            <span class="keyword">for</span> (Node&lt;E&gt; x = first; x != <span class="keyword">null</span>; x = x.next) &#123;</span><br><span class="line">                <span class="keyword">if</span> (o.equals(x.item)) &#123;</span><br><span class="line">                    unlink(x);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Unlinks non-null node x.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">E <span class="title">unlink</span><span class="params">(Node&lt;E&gt; x)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// assert x != null;</span></span><br><span class="line">        <span class="keyword">final</span> E element = x.item;</span><br><span class="line">        <span class="comment">// 局部保存被删除节点的前后节点</span></span><br><span class="line">        <span class="keyword">final</span> Node&lt;E&gt; next = x.next;</span><br><span class="line">        <span class="keyword">final</span> Node&lt;E&gt; prev = x.prev;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">if</span> (prev == <span class="keyword">null</span>) &#123;<span class="comment">// prev 为 null 说明 x 节点为 first 节点，则删除后，next 为 first</span></span><br><span class="line">            first = next;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;<span class="comment">// 否则 prev的下一个元素为x的next</span></span><br><span class="line">            prev.next = next;</span><br><span class="line">            x.prev = <span class="keyword">null</span>;<span class="comment">// 设为 null，方便GC</span></span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="keyword">if</span> (next == <span class="keyword">null</span>) &#123;<span class="comment">// next 为null说明x节点为 last 节点，则删除后，next 为 prev</span></span><br><span class="line">            last = prev;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;<span class="comment">// 否则 next 的上一个元素为x的prev</span></span><br><span class="line">            next.prev = prev;</span><br><span class="line">            x.next = <span class="keyword">null</span>;<span class="comment">// 设为 null，方便GC</span></span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        x.item = <span class="keyword">null</span>;<span class="comment">// 设为 null，方便GC</span></span><br><span class="line">        size--;</span><br><span class="line">        modCount++;<span class="comment">// 链表结构发生改变</span></span><br><span class="line">        <span class="keyword">return</span> element;<span class="comment">//返回被删除节点的数据体</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其他的移除方法：</p>
<ul>
<li>clear()： 从此列表中移除所有元素。</li>
<li>remove()：获取并移除此列表的头（第一个元素）。</li>
<li>remove(int index)：移除此列表中指定位置处的元素。</li>
<li>remove(Objec o)：从此列表中移除首次出现的指定元素（如果存在）。</li>
<li>removeFirst()：移除并返回此列表的第一个元素。</li>
<li>removeFirstOccurrence(Object o)：从此列表中移除第一次出现的指定元素（从头部到尾部遍历列表时）。</li>
<li>removeLast()：移除并返回此列表的最后一个元素。</li>
<li>removeLastOccurrence(Object o)：从此列表中移除最后一次出现的指定元素（从头部到尾部遍历列表时）。</li>
</ul>
<h3 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h3><p>查询的方法非常简单，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        checkElementIndex(index);<span class="comment">// 检查索引index 是否在 [0,size] 区间内</span></span><br><span class="line">        <span class="keyword">return</span> node(index).item;<span class="comment">//利用双向链表的特性，进行更快的遍历</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其它的查询方法：</p>
<ul>
<li>getFirst()：返回此列表的第一个元素。</li>
<li>getLast()：返回此列表的最后一个元素。</li>
<li>indexOf(Object o)：返回此列表中首次出现的指定元素的索引，如果此列表中不包含该元素，则返回 -1。</li>
<li>lastIndexOf(Object o)：返回此列表中最后出现的指定元素的索引，如果此列表中不包含该元素，则返回 -1。</li>
</ul>
<h3 id="迭代器-listIterator"><a href="#迭代器-listIterator" class="headerlink" title="迭代器 listIterator"></a>迭代器 listIterator</h3><p>关于集合的快速失败机制的详细了解可以<a href="Java%E9%9B%86%E5%90%88%E5%AD%A6%E4%B9%A0%E4%B9%8Bfail-fast.md">看这里</a></p>
<p>iterator() 调用的其实是 listIterator() 方法，对于不同的实现类，都会实现不同的方法，但是其原理是一致的，<br>都是为了防止多线程操作同一个集合而出现的问题</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractSequentialList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">List</span>&lt;<span class="title">E</span>&gt;, <span class="title">Deque</span>&lt;<span class="title">E</span>&gt;, <span class="title">Cloneable</span>, <span class="title">java</span>.<span class="title">io</span>.<span class="title">Serializable</span></span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> ListIterator&lt;E&gt; <span class="title">listIterator</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        checkPositionIndex(index);<span class="comment">// 检查索引的正确性[0, size]</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ListItr(index);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">ListItr</span> <span class="keyword">implements</span> <span class="title">ListIterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> Node&lt;E&gt; lastReturned;<span class="comment">// 记录上次返回的元素</span></span><br><span class="line">        <span class="keyword">private</span> Node&lt;E&gt; next;<span class="comment">// 记录下一个元素</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">int</span> nextIndex;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">int</span> expectedModCount = modCount;<span class="comment">// 用来判断迭代过程中，是否有对元素的改动(fail-fast)</span></span><br><span class="line">    </span><br><span class="line">        ListItr(<span class="keyword">int</span> index) &#123;</span><br><span class="line">            <span class="comment">// assert isPositionIndex(index);</span></span><br><span class="line">            next = (index == size) ? <span class="keyword">null</span> : node(index);<span class="comment">//初始化next，以便在next方法中返回</span></span><br><span class="line">            nextIndex = index;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> nextIndex &lt; size;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">public</span> E <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            checkForComodification();<span class="comment">// 判断是否有对元素的改动，有则抛出异常</span></span><br><span class="line">            <span class="keyword">if</span> (!hasNext())</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">    </span><br><span class="line">            lastReturned = next;<span class="comment">// next()当中的next元素就是要返回的结果</span></span><br><span class="line">            next = next.next;</span><br><span class="line">            nextIndex++;</span><br><span class="line">            <span class="keyword">return</span> lastReturned.item;</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">// 省略其它代码。。。</span></span><br><span class="line">    </span><br><span class="line">        <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">checkForComodification</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="有关队列、栈的方法"><a href="#有关队列、栈的方法" class="headerlink" title="有关队列、栈的方法"></a>有关队列、栈的方法</h3><ul>
<li>peek():返回第一个节点,若LinkedList的大小为0,则返回null</li>
<li>peekFirst():返回第一个节点,若LinkedList的大小为0,则返回null</li>
<li>peekLast():返回最后一个节点,若LinkedList的大小为0,则返回null</li>
<li>element():返回第一个节点,若LinkedList的大小为0,则抛出异常</li>
<li>poll():删除并返回第一个节点,若LinkedList的大小为0,则返回null</li>
<li>pollFirst():删除并返回第一个节点,若LinkedList的大小为0,则返回null</li>
<li>pollLast():删除并返回最后一个节点,若LinkedList的大小为0,则返回null</li>
<li>offer(E e):将e添加双向链表末尾</li>
<li>offerFirst(E e):将e添加双向链表开头</li>
<li>offerLast(E e):将e添加双向链表末尾</li>
<li>push(E e):将e插入到双向链表开头</li>
<li>pop():删除并返回第一个节点</li>
</ul>
<p>LinkedList 作为 FIFO(先进先出) 的队列, 下表的方法等效：</p>
<table>
<thead>
<tr>
<th>队列方法</th>
<th>等效方法</th>
</tr>
</thead>
<tbody><tr>
<td>add(e)</td>
<td>addLast(e)</td>
</tr>
<tr>
<td>offer(e)</td>
<td>offerLast(e)</td>
</tr>
<tr>
<td>remove()</td>
<td>removeFirst()</td>
</tr>
<tr>
<td>poll()</td>
<td>pollFirst()</td>
</tr>
<tr>
<td>element()</td>
<td>getFirst()</td>
</tr>
<tr>
<td>peek()</td>
<td>peekFirst()</td>
</tr>
</tbody></table>
<p>LinkedList 作为 LIFO(后进先出) 的栈, 下表的方法等效：</p>
<table>
<thead>
<tr>
<th>栈方法</th>
<th>等效方法</th>
</tr>
</thead>
<tbody><tr>
<td>push(e)</td>
<td>addFirst(e)</td>
</tr>
<tr>
<td>pop()</td>
<td>removeFirst()</td>
</tr>
<tr>
<td>peek()</td>
<td>peekFirst()</td>
</tr>
</tbody></table>
<h3 id="LinkedList-的遍历方法和性能比较"><a href="#LinkedList-的遍历方法和性能比较" class="headerlink" title="LinkedList 的遍历方法和性能比较"></a>LinkedList 的遍历方法和性能比较</h3><h3 id="使用示例"><a href="#使用示例" class="headerlink" title="使用示例"></a>使用示例</h3><h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><ol>
<li>LinkedList 实际上是通过双向链表去实现的。它包含一个非常重要的内部类：<code>Node</code>。<code>Node</code> 是双向链表节点所对应的数据结构，<br>它包括的属性有：当前节点所包含的值，上一个节点，下一个节点。</li>
<li>从 LinkedList 的实现方式中可以发现，它不存在LinkedList容量不足的问题。</li>
<li>LinkedList 的克隆函数，即是将全部元素克隆到一个新的LinkedList对象中。</li>
<li>LinkedList 实现java.io.Serializable。当写入到输出流时，先写入“容量”，再依次写入“每一个节点保护的值”；<br>当读出输入流时，先读取“容量”，再依次读取“每一个元素”。</li>
<li>由于 LinkedList 实现了Deque，而 Deque 接口定义了在双端队列两端访问元素的方法。提供插入、移除和检查元素的方法。<br>每种方法都存在两种形式：一种形式在操作失败时抛出异常，另一种形式返回一个特殊值（null 或 false，具体取决于操作）。</li>
</ol>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/19/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/19/">19</a><span class="page-number current">20</span><a class="page-number" href="/page/21/">21</a><span class="space">&hellip;</span><a class="page-number" href="/page/24/">24</a><a class="extend next" rel="next" href="/page/21/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>


<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
